0
有人可以幫助下面的代碼。我不認爲信號正在被我的線程工作人員看到。我期望看到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;
}
你'pthread_mutex_t mutexqueue'和'主()'遮蓋同名的全局變量'pthread_cond_t的condworker'。 – EOF