【发布时间】:2019-06-15 08:36:52
【问题描述】:
我创建了一个用于记录的简单 c++ 程序。我在 for 循环中创建线程,该循环在驱动程序文件 test.cpp 中运行 1000 次。 pthread_create 调用tt.cpp 中的打印函数,它将输入参数写入file.txt。
我希望同步线程。
我尝试使用 pthread_join 同步线程,但我希望在不使用连接的情况下同步线程。
我知道如果一个线程被锁定,很多线程会一直等待直到它被解锁,在那个线程被解锁之后,任何一个等待的线程都会锁定这个函数。因此,我尝试在tt.cpp 中使用静态整数变量,并尝试将其与输入参数进行比较,以便可以使用pthread_cond_wait 和pthread_wait_signal,但比较时出现分段错误。
/* if(j == *((int *)input)))
This comparison gave me a segmentation fault */
-------------------------test.cpp---------------------------------
#include "thr.h"
pthread_mutex_t loc;
FILE *thePrintFile = NULL;
int main()
{
pthread_mutex_init(&loc,NULL);
pthread_t p;
thePrintFile = fopen("file.txt","r+");
for(int i =0; i<1000;i++)
{
pthread_create(&p,NULL,print,(void *)i);
}
for(int k = 0; k<100000;k++);
/* i have used it to ensure that the main thread
doesn't exit before the pthreads finish writing */
return 0;
}
------------------------tt.cpp------------------------------------
#include "thr.h"
extern pthread_mutex_t loc;
extern FILE *thePrintFile;
void* print(void *input)
{
if(pthread_mutex_trylock(&loc) == 0)
{
fprintf(thePrintFile,"%s%d\n",(int *)input);
fflush(thePrintFile);
pthread_mutex_unlock(&loc);
}
}
-----------------------------thr.h--------------------------------
#ifndef THR_H_INCLUDED
#define THR_H_INCLUDED
void* print(void *input);
#endif
下面给出的是 file.txt 的一部分。
1
5
9
10
11
12
13
14
15
16
18
19
20
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
21
201
202
【问题讨论】:
-
问题是什么?
-
对不起,如果我的问题不清楚。我希望线程按顺序工作,比如首先它应该写 0 然后 1,2,3 .....等等。
-
您表明您在某条线路上遇到了分段错误。该行不在您发布的实际代码中。然后你的打印部分有一个 void * 返回类型,但你什么都不返回。
-
是 C 还是 C++ ?您将其标记为 C++,但代码更像 C
-
创建 1000 个线程可能不是一个好主意。
标签: c++ synchronization pthreads mutex