首页 > 代码库 > 【Linux】一个简单的线程创建和同步的例子

【Linux】一个简单的线程创建和同步的例子

 

最近很多精力在Linux上,今天简单看了一下Linux上的线程和同步,其实不管windows还是Linux,OS层面的很多原理和概念都是相同的,很多windows之上的经验和概念完全可以移植到Linux上。

今天用到了创建线程和一个阻塞式的线程同步函数。

 

 

用到的几个函数

#include <pthread.h> //创建线程int  pthread_create(pthread_t* thread,                   /*线程标ID,   pthread_t  pthread_self(void) 可获取当前线程ID*/pthread_attr_t* attr,              /*线程属性,如无需要可为0 */void* (*start_routine)(void*), /*线程函数*/void* arg                               /*线程函数参数*/);返回值成功: 0失败:错误代码//终止线程void  pthread_exit(void* retval   /*线程返回时带回的值,注意局部变量等问题*/)//阻塞式线程同步int  pthread_join(pthread_t  th,  /*pthread_create 函数第一个参数带回的值*/void** thread  /*线程函数返回值,内存在此函数内部分配*/) //获取当前线程IDpthread_t   pthread_self(void)

 

 

 

 

 

贴出代码

   /*a demo for Linux MultiThread   */  3 #include <iostream>  4 #include <pthread.h>  5 #include <stdlib.h>  6 #include <unistd.h>  7 using namespace std;  8   9 //thread function 10 void*  start_routine(void* p) 11 { 12     if (0 == p) 13         return 0; 14  15     size_t nLoops = *( (size_t*) p ); 16  17     for (size_t i = 0; i < nLoops; ++ i) 18     { 19         cout << i << endl; 20         usleep(1000 * 800);   //800 ms   21     } 22  23     cout << endl << "This thread ID is " << pthread_self() << endl; 24  25     return 0; 26 } 27  28  29 int main() 30 { 31     pthread_t ptThread1; 32     size_t* pLoops = new size_t(10); 33     int nRet = pthread_create(&ptThread1, 0, start_routine, (void*)pLoops); 34     if (0 != nRet) 35         cerr << endl << "create thread error!" << endl; 36     else 37         cerr << endl << "create thread successfully, return value code is " << nRet  38             << endl << "thread ID is " << ptThread1 << endl; 39  40     if (0 == nRet) 41     { 42         cout << endl << "wait for thread " << ptThread1 << endl; 43         void* pRetVal = 0; 44         int nJoinRet = pthread_join(ptThread1, (void**)&pRetVal); 45         cout << endl << "thread " << ptThread1 << " finished !" << endl; 46         cout << "thread return value is " << (char*)pRetVal << endl; 47     } 48     cout << endl; 49  50     delete pLoops; 51     pLoops = 0; 52  53     system("ls"); 54  55     return 0; 56 }

 

 

 

执行结果

 

 

 PS: 注意可能需要在g++编译参数上加上  -lpthread

  

 

 

【Linux】一个简单的线程创建和同步的例子