您不应该像这样重用线程参数,这将导致数据争用。请改用这样的arg数组。见
how not to use the pthread_create arg
这是一个简单的比赛例子,在我的机器上,它打印2,3,3。
#include <pthread.h>
#include <stdexcept>
#include <iostream>
using std::cout;
const int NR_THREADS = 3;
pthread_t tid[NR_THREADS];
void* threadfunc(void* arg)
{
int val = *(int* )arg;
cout << "Thread got arg " << val << '\n';
return 0;
}
int main()
{
int retval;
for (int i = 0; i < NR_THREADS; i++) {
retval = pthread_create(&tid[i], NULL, threadfunc, &i);
if (retval) throw std::runtime_error("Pthread create failed!");
}
for (int i = 0; i < NR_THREADS; i++) {
pthread_join(tid[i], NULL);
if (retval) throw std::runtime_error("Pthread join failed!");
}
return 0;
}
这里是避免构建错误所需的差异(还必须更改头位置和ubuntu上的.so lib位置,并删除-framework gcc标志)
diff pdfcrack/pdfcrack.c pdfcrack_modded/pdfcrack.c
116c116
< pthread_t thread_id = malloc(sizeof(pthread_t) * device_count);
---
> pthread_t* thread_id = malloc(sizeof(pthread_t) * device_count);
154c154
< pthread_join(&thread_id[i], &status);
---
> pthread_join(thread_id[i], &status);