有人可以帮助解决下面的代码。我不认为我的线程工作者正在看到信号。我希望看到STEQUESIZE 1打印,但它永远不会发生。任何帮助将不胜感激。
输出是:
线程已启动 互斥锁定 完成
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <string.h>
#include <getopt.h>
#include <pthread.h>
#include <errno.h>
// GLOBALS
pthread_mutex_t mutexqueue;
pthread_cond_t condworker;
pthread_t *threadIDs;
int STEQUESIZE=0;
void* worker(void *arg) {
fprintf(stdout,"Thread Started\n");
fflush(stdout);
while (1) {
pthread_mutex_lock(&mutexqueue);
fprintf(stdout,"mutex locked\n"); fflush(stdout);
while(STEQUESIZE == 0);
pthread_cond_wait(&condworker, &mutexqueue);
fprintf(stdout,"STEQUESIZE %d\n",STEQUESIZE);
fflush(stdout);
STEQUESIZE--;
pthread_mutex_unlock(&mutexqueue);
}
}
int main(int argc, char **argv) {
int nthreads = 1;
STEQUESIZE=0;
pthread_mutex_t mutexqueue = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condworker = PTHREAD_COND_INITIALIZER;
threadIDs = (pthread_t *)malloc(sizeof(pthread_t)*nthreads);
int j;
for(j=0; j< nthreads;j++)
pthread_create(&threadIDs[j], NULL, worker, NULL);
sleep(2);
pthread_mutex_lock(&mutexqueue);
STEQUESIZE=1;
pthread_cond_signal(&condworker);
pthread_mutex_unlock(&mutexqueue);
printf("done\n");
while(1);
return 0;
}
答案 0 :(得分:0)
感谢评论回答了我的问题。我的全局变量和局部变量名称相同。
// GLOBALS
pthread_mutex_t mutexqueue;
pthread_cond_t condworker;
pthread_t *threadIDs;
int STEQUESIZE=0;
然后
int main(int argc, char **argv) {
int nthreads = 1;
STEQUESIZE=0;
pthread_mutex_t mutexqueue = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condworker = PTHREAD_COND_INITIALIZER;