码迷,mamicode.com
首页 > 编程语言 > 详细

线程初级基础(一)

时间:2014-09-16 01:30:19      阅读:243      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   os   ar   for   div   sp   

一,单线程例子

 

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <pthread.h>
using namespace std;

void *thread_func(void *arg)
{
    for(int i=0; i<3; i++)
    {
        sleep(1);
        cout<<"Running in thread"<<endl;
    }

    return NULL;
}

int main()
{
    pthread_t tid1;
    if(pthread_create(&tid1, NULL, thread_func, NULL) != 0)
    {
        cout<<"thread create error"<<endl;
        return -1;
    }

    for(int i=0; i<3; i++)
    {
        cout<<"Running in main process"<<endl;
        sleep(1);
    }

    pthread_join(tid1, NULL);
    return 0;
}

输出结果:

[root@localhost thread]# ./a.out 
Running in main process
Running in main process
Running in thread
Running in thread
Running in main process
Running in thread
[root@localhost thread]# ./a.out 
Running in main process
Running in thread
Running in main process
Running in thread
Running in main process
Running in thread
[root@localhost thread]# ./a.out 
Running in main process
Running in thread
Running in main process
Running in main process
Running in thread
Running in thread

 

线程初级基础(一)

标签:style   blog   color   io   os   ar   for   div   sp   

原文地址:http://www.cnblogs.com/jacklikedogs/p/3974040.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!