简体   繁体   English

在C中使用互斥锁同步两个pthread

[英]Synchronizing two pthreads using mutex in C

Need help with synchronizing two threads with mutex. 在使用互斥量同步两个线程时需要帮助。 Iam new to C and mutexes and Im not sure what to do here. 我是C和互斥锁的新手,我不确定在这里做什么。 The code has two threads that counts to ten and prints out each number, but is not synch, so it will not print synchronized, it is half synched. 该代码有两个线程,总数为10,并打印出每个数字,但不同步,因此不会同步打印,而是同步一半。 Means that i only get trouble in the end, sometimes it prints 8..9..11, 8..9..10..10 and so on. 意味着我最终只会遇到麻烦,有时会打印8..9..11、8..9..10..10等。

I cannot make changes to the raw code, if you take away the lines about mutexes, that is the raw code. 如果您删除了关于互斥锁的代码,那我就无法更改原始代码。 I can only add lines about mutexes. 我只能添加关于互斥锁的行。

#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;
}

With the condition outside your mutex you may not be receiving the correct values. 在互斥锁之外的情况下,您可能收不到正确的值。 A guaranteed way to ensure the loop operates in-order would be the following change to writeloop : 确保循环按顺序运行的保证方法是对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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM