简体   繁体   English

使用互斥锁进行pthread同步

[英]pthread synchronization using mutex

I was trying to create 2 threads and calling the same function which increments a counter "count" from a for loop. 我试图创建2个线程并调用相同的函数,该函数从for循环中增加计数器“ count”。 But every time I run this code the value of the counter is different. 但是每次我运行此代码时,计数器的值都不同。 I try to use mutex to have synchronization between threads when they increment the global static variable "count" but still value is different. 当它们增加全局静态变量“ count”但值仍然不同时,我尝试使用互斥锁在线程之间进行同步。

static int  count;
pthread_mutex_t count_mutex;

 void increment()
 {
    pthread_mutex_lock(&count_mutex);
    count++;
    pthread_mutex_unlock(&count_mutex);
}

void *myThreadFun1(void *var)
{
    printf("Thread1\n");
    for(int i=0; i< 10000;i++)
    {
        increment();
    }
    return;
}

int main()
{
    pthread_t tid1;
    pthread_t tid2;
    pthread_create(&tid1, NULL, myThreadFun1, NULL);
    // sleep(1);
    pthread_create(&tid2, NULL, myThreadFun1, NULL);
    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);

    printf("\n%d",count);
    exit(0);
}

Output is never 20000 if I don't sleep between threads. 如果我不睡在线程之间,则输出永远不会是20000。

In java there is "synchronized" keyword we can use, but how to achieve same in C ? 在Java中,我们可以使用“ synchronized”关键字,但是如何在C中实现相同的关键字?

pthread_mutex_t requires initialization before use. pthread_mutex_t在使用前需要进行初始化。 It must start unlocked and unbound. 它必须开始解锁并解除绑定。 There is a call, pthread_mutex_init(&theMutex) that can do this, or a predefined value can be assigned for static init: PTHREAD_MUTEX_INITIALIZER 有一个调用pthread_mutex_init(&theMutex)可以执行此操作,或者可以为静态init分配预定义的值:PTHREAD_MUTEX_INITIALIZER

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

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