【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 /*线程函数返回值,内存在此函数内部分配*/
)
//获取当前线程ID
pthread_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
**********************技术交流请 email:cuihao0532#163.com 欢迎转载,转载请注明出处!***************************** 如果对本文满意请扫描文章左侧【二维码添加微信】获取更多好玩、有趣、有益、有营养的料,
你我共同成长!Y(^_^)Y
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗