首页 > 代码库 > 线程初级基础(一)

线程初级基础(一)

一,单线程例子

 

#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 processRunning in main processRunning in threadRunning in threadRunning in main processRunning in thread[root@localhost thread]# ./a.out Running in main processRunning in threadRunning in main processRunning in threadRunning in main processRunning in thread[root@localhost thread]# ./a.out Running in main processRunning in threadRunning in main processRunning in main processRunning in threadRunning in thread

 

线程初级基础(一)