#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 如何在scanpy上做差异基因和通路富集?
- ¥20 关于#硬件工程#的问题,请各位专家解答!
- ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
- ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
- ¥30 截图中的mathematics程序转换成matlab
- ¥15 动力学代码报错,维度不匹配
- ¥15 Power query添加列问题
- ¥50 Kubernetes&Fission&Eleasticsearch
- ¥15 報錯:Person is not mapped,如何解決?
- ¥15 c++头文件不能识别CDialog