#include
2 #include
3 #include
4 #include
5 #include
6
7 void *thread_function(void *arg);
8 void print(pid_t);
9 sem_t *sem;
10 int val;
11 pthread_t a_thread;
12
13 int main(int argc,char *argv[])
14 {
15 int n = 0;
16
17 if(argc != 2)
18 {
19 printf("please input a file name!\n");
20 exit(1);
21 }
22 sem = sem_open(argv[1],O_CREAT,0644,3);
23
24 while(n++<5)
25 {
26 if((pthread_create(&a_thread,NULL,thread_function,NULL)) != 0)
27 {
28 perror("Thread creation failed");
29 exit(1);
30 }
31 }
32
33 pthread_join(a_thread,NULL);
34 sem_close(sem);
35 sem_unlink(argv[1]);
36 }
37
38 void *thread_function(void *arg)
39 {
40 sem_wait(sem);
41 print();
42 sleep(1);
43 sem_post(sem);
44 printf("I'm finished,my tid is %d\n",pthread_self());
45 }
46
47 void print()
{
49 printf("I get it,my tid is %d\n",pthread_self());
50 sem_getvalue(sem,&val);
51 printf("Now the value have %d\n",val);
52 }
下面代码哪出错了啊?linux的多线程
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
2条回答
- 普通网友 2017-05-08 09:43关注
OK try this
compile with gcc thd.c -o thd -lpthread -lrt
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <semaphore.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> void *thread_function(void *arg); void print(); sem_t *sem; int val; pthread_t a_thread; int main(int argc,char *argv[]) { int n = 0; if(argc != 2) { printf("please input a file name!\n"); exit(1); } sem = sem_open(argv[1],O_CREAT,0644,3); while(n++<5) { if((pthread_create(&a_thread,NULL,thread_function,NULL)) != 0) { perror("Thread creation failed"); exit(1); } } pthread_join(a_thread,NULL); sem_close(sem); sem_unlink(argv[1]); } void *thread_function(void *arg) { sem_wait(sem); print(); sleep(1); sem_post(sem); printf("I'm finished,my tid is %d\n",pthread_self()); } void print() { printf("I get it,my tid is %d\n",pthread_self()); sem_getvalue(sem,&val); printf("Now the value have %d\n",val); }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥20 删除和修改功能无法调用
- ¥15 kafka topic 所有分副本数修改
- ¥15 小程序中fit格式等运动数据文件怎样实现可视化?(包含心率信息))
- ¥15 如何利用mmdetection3d中的get_flops.py文件计算fcos3d方法的flops?
- ¥40 串口调试助手打开串口后,keil5的代码就停止了
- ¥15 电脑最近经常蓝屏,求大家看看哪的问题
- ¥60 高价有偿求java辅导。工程量较大,价格你定,联系确定辅导后将采纳你的答案。希望能给出完整详细代码,并能解释回答我关于代码的疑问疑问,代码要求如下,联系我会发文档
- ¥50 C++五子棋AI程序编写
- ¥30 求安卓设备利用一个typeC接口,同时实现向pc一边投屏一边上传数据的解决方案。
- ¥15 SQL Server analysis services 服务安装失败