1

需要帮助将两个线程与互斥锁同步。我是 C 和互斥锁的新手,我不确定在这里做什么。该代码有两个线程,计数到十并打印出每个数字,但不同步,所以它不会打印同步,它是半同步的。意味着我最终只会遇到麻烦,有时它会打印 8..9..11、8..9..10..10 等等。

我不能对原始代码进行更改,如果您删除有关互斥锁的行,那就是原始代码。我只能添加关于互斥锁的行。

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

pthread_mutex_t mutex;

int g_ant = 0;

void *writeloop(void *arg) {
    while(g_ant < 10) {
        pthread_mutex_lock(&mutex);
        g_ant++;
        usleep(rand()%10);
        printf("%d\n", g_ant);
        pthread_mutex_unlock(&mutex);
    }
    exit(0);
}

int main(void)
{
    pthread_t tid;
    pthread_mutex_init(&mutex, NULL);
    pthread_create(&tid, NULL, writeloop, NULL);
    writeloop(NULL);
    pthread_join(tid, NULL);
    pthread_mutex_destroy(&mutex);
    return 0;
}
4

1 回答 1

1

在互斥锁之外的情况下,您可能没有收到正确的值。确保循环按顺序运行的有保证的方法是将以下更改为writeloop

void writeloop(void *arg) {
    while (g_ant < 10) {
        pthread_mutex_lock(&mutex);
        if (g_ant >= 10) {
            pthread_mutex_unlock(&mutex);
            break;
        }

        g_ant++;
        usleep(rand()%10);
        printf("%d\n", g_ant);
        pthread_mutex_unlock(&mutex);
    }
}
于 2013-02-12T19:29:39.733 回答