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

 

最近不少精力在Linux上,今天简单看了一下Linux上的线程和同步,其实无论windows仍是Linux,OS层面的不少原理和概念都是相同的,不少windows之上的经验和概念彻底能够移植到Linux上。ios

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

 

 

用到的几个函数函数

#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 /*线程函数返回值,内存在此函数内部分配*/ ) //获取当前线程ID  pthread_t pthread_self(void)

 

 

 

 

 

贴出代码oop

 /*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 }

 

 

 

执行结果spa

 

 

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

相关文章
相关标签/搜索