并行线程程序运行一段时间,然后摊
有一个程序,我就这一工作后,我启动它,工作了一段时间,然后摊位。下面是该程序的简化版本:并行线程程序运行一段时间,然后摊
#include <cstdlib>
#include <iostream>
#include <pthread.h>
pthread_t* thread_handles;
pthread_mutex_t mutex;
pthread_cond_t cond_var = PTHREAD_COND_INITIALIZER;
int thread_count;
const int some_count = 77;
const int numb_count = 5;
int countR = 0;
//Initialize threads
void InitTh(char* arg[]){
/* Get number of threads */
thread_count = strtol(arg[1], NULL, 10);
/*Allocate space for threads*/
thread_handles =(pthread_t*) malloc (thread_count*sizeof(pthread_t));
}
//Terminate threads
void TermTh(){
for(long thread = 0; thread < thread_count; thread++)
pthread_join(thread_handles[thread], NULL);
free(thread_handles);
}
void* DO_WORK(void* replica) {
/*Does something*/
pthread_mutex_lock(&mutex);
countR++;
if (countR == numb_count) pthread_cond_broadcast(&cond_var);
pthread_mutex_unlock(&mutex);
}
//Some function
void FUNCTION(){
pthread_mutex_init(&mutex, NULL);
for(int k = 0; k < some_count; k++){
for(int j = 0; j < numb_count; j++){
long thread = (long) j % thread_count;
pthread_create(&thread_handles[thread], NULL, DO_WORK, (void *)j);;
}
/*Wait for threads to finish their jobs*/
pthread_mutex_lock(&mutex);
if (countR < numb_count) while(pthread_cond_wait(&cond_var,&mutex) != 0);
countR = 0;
pthread_mutex_unlock(&mutex);
/*Does more work*/
}
pthread_cond_destroy(&cond_var);
pthread_mutex_destroy(&mutex);
}
int main(int argc, char* argv[]) {
/*Initialize threads*/
InitTh(argv);
/*Do some work*/
FUNCTION();
/*Treminate threads*/
TermTh();
return 0;
}
当some_count
,(在我的具体情况,)小于76,则程序工作正常,但如果我指定一个较大的值的程序,如前面提到的,工作一段时间然后停止。也许有人可以指出我做错了什么?
我想你应该初始化线程数numb_count
而不是argv
然后更换
long thread = (long) j % thread_count;
与
long thread = (long) j;
会不知道它解决它,但它需要反正...
此外,它不是关于数字76或77,你有线程使用中的竞争条件。 让说,你一个线程到了点“DO_WORK”当他解开互斥,但他仍然没有从这个函数返回(表示线程仍在运行...)。那么你可以尝试使用下一次迭代中创建相同的线程:
pthread_create(&thread_handles[thread], NULL, DO_WORK, (void *)j);
固定,变化:
pthread_mutex_lock(&mutex);
if (countR < numb_count) while(pthread_cond_wait(&cond_var,&mutex) != 0);
countR = 0;
pthread_mutex_unlock(&mutex);
到:
pthread_mutex_lock(&mutex);
if (countR < numb_count) while(pthread_cond_wait(&cond_var,&mutex) != 0);
countR = 0;
for(long thread = 0; thread < numb_count; thread++)
pthread_join(thread_handles[thread], NULL);
pthread_mutex_unlock(&mutex);
非常感谢它的帮助下,我的意思是,现在的方案致力于通过更大量的循环,但仍最终档可能还有另外一个问题在这里再次感谢它。是非常有帮助! –
你应该(如果你没有的话)删除for循环从TermTH()或程序会卡住正在等待中,而没有线程运行一个线程来完成他的工作... –
诗如果问题已解决请选择答案作为“答案”,这样它将接近于防止他人浪费时间来解决它。 –
在
long thread = (long) j % thread_count;
pthread_create(&thread_handles[thread], NULL, DO_WORK, (void *)j);;
可以“覆盖”初始化线程句柄,这取决于你的实际线程数参数。
你可以尝试使用helgrind来分析它。
Valgrind的安装,然后启动的valgrind --tool = helgrind yourproject,看看helgrind吐出
你既不正确初始化您的互斥量(这里未导致错误),也不会存储您正确地创建线程。试试这个:
for(int count = 0; count < thread_count; ++count) {
pthread_create(&thread_handles[count], NULL, DO_WORK, (void *)(count % numb_count));
}
什么是你通常在运行时使用的输入?我的意思是Thread_count的价值是什么? –
从二到四。 –
那么你如何期望在你的malloc二到四时同时运行5个线程(j循环)? –