#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); }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 虚幻5 UE美术毛发渲染
- ¥15 CVRP 图论 物流运输优化
- ¥15 Tableau online 嵌入ppt失败
- ¥100 支付宝网页转账系统不识别账号
- ¥15 基于单片机的靶位控制系统
- ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
- ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
- ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
- ¥15 手机接入宽带网线,如何释放宽带全部速度
- ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测