这是我创建的一些代码,目的只是为了测试有关条件变量和互斥对象的某些内容。它只是应该计数到10,但是由于某些原因,工作线程会继续在printlock互斥锁上停止,因为在等待printcond时主线程没有醒来。
这是我的输出:

"I have this many threads: 7
This is my 1 time running, and my number is 0!
This is my 2 time running, and my number is 1!"

我一定缺少关于条件变量的显而易见的东西。我曾尝试在发出信号信号printcond后解锁工作线程中的printlock,这使代码得以运行,但随后主线程仅输出最后一个值即可。我希望主线程为所有1-10打印“我得到的数字”。我怎么做?我无法理解这些内容的逻辑结构,因此我四处寻找解决方案。任何帮助表示赞赏。
pthread_mutex_t varlock;
pthread_mutex_t printlock;
pthread_cond_t printcond;

void *worker(void *args)
{
int * count = args;
int run = 1;
while(1==1)
{
    pthread_mutex_lock(&varlock);
    if(*count == 10)
    {
        pthread_mutex_unlock(&varlock);
        printf("I am a thread exiting\n");
        return NULL;
    }
    else
    {
        printf("This is my %d time running, and my number is %d!\n", run, *count);
        pthread_mutex_lock(&printlock);
        pthread_cond_signal(&printcond);
        *count = *count +1;
        run++;
    }
    pthread_mutex_unlock(&varlock);
}
}

int main(int argc, char **argv)
{
int num = 7;
printf("I have this many threads: %d\n", num);
int * count = malloc(sizeof(int));
*count = 0;
if (pthread_mutex_init(&varlock, NULL) != 0)
{
    printf("mmult: Failed initializing mutex\n");
    return 1;
}
if (pthread_mutex_init(&printlock, NULL) != 0)
{
    printf("mmult: Failed initializing mutex\n");
    return 1;
}
pthread_mutex_lock(&printlock);
int err=pthread_cond_init(&printcond, NULL);
//Create the threads
pthread_t tid[num];
int i;
for(i = 0; i < num; i++)
{
    err = pthread_create(&(tid[i]),NULL,worker, count);
    if(err)
    {
        perror("mmult: Failed creating thread\n");
        return 1;
    }
}
while(1==1)
{
    if(*count == 10)
    {
        break;
    }
    pthread_cond_wait(&printcond, &printlock);
    printf("The number I got is %d.\n", *count);
    pthread_mutex_unlock(&printlock);
}
//Join all the threads
int status;
for(i = 0; i < num; i++)
{
    pthread_join(tid[i],(void **)&status);
}
printf("Now that I have finished, the count is %d.\n", *count);
return 0;
}

最佳答案

您有很多错误,但是最明显的错误是您的第二个while(1==1)循环可解锁互斥锁,但不会将其锁定。因此,如果您循环播放,将解锁已经解锁的互斥锁。那是一个错误。

您的第一个while(1==1)循环也是 buggy 。解锁互斥锁只是为了立即再次锁定它。您认为这样做有什么目的?

关于c - Linux C中的条件变量解锁,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41111595/

10-16 16:03