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

时间:2023-03-08 23:27:19
【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                               /*线程函数参数*/

);

返回值

成功: 

失败:错误代码

//终止线程

void  pthread_exit(

void* retval   /*线程返回时带回的值,注意局部变量等问题*/

)

//阻塞式线程同步

int  pthread_join(

pthread_t  th,  /*pthread_create 函数第一个参数带回的值*/

void** thread  /*线程函数返回值,内存在此函数内部分配*/

)

//获取当前线程ID

pthread_t   pthread_self(void)

贴出代码

   /*a demo for Linux MultiThread   */
#include <iostream>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
using namespace std; //thread function
void* start_routine(void* p)
{
if ( == p)
return ; size_t nLoops = *( (size_t*) p ); for (size_t i = ; i < nLoops; ++ i)
{
cout << i << endl;
usleep( * ); //800 ms
} cout << endl << "This thread ID is " << pthread_self() << endl; return ;
} int main()
{
pthread_t ptThread1;
size_t* pLoops = new size_t();
int nRet = pthread_create(&ptThread1, , start_routine, (void*)pLoops);
if ( != nRet)
cerr << endl << "create thread error!" << endl;
else
cerr << endl << "create thread successfully, return value code is " << nRet \
<< endl << "thread ID is " << ptThread1 << endl; if ( == nRet)
{
cout << endl << "wait for thread " << ptThread1 << endl;
void* pRetVal = ;
int nJoinRet = pthread_join(ptThread1, (void**)&pRetVal);
cout << endl << "thread " << ptThread1 << " finished !" << endl;
cout << "thread return value is " << (char*)pRetVal << endl;
}
cout << endl; delete pLoops;
pLoops = ; system("ls"); return ;
}

执行结果

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

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