c - 如何控制互斥量的加锁和解锁?

标签 c linux mutex

<分区>

我有一个关于基本互斥锁和解锁示例的问题!

#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
#define TNUM 4

pthread_mutext_t mutx;
int cnt = 0;


void *t_function(void *data)
{

    while(cnt < 1000)
    {
        pthread_mutex_lock(&mutx);
        cnt++;
        pthread_mutex_unlock(&mutx);
    }

}

int main()
{
    pthread_t p_thread[TNUM];
    int thr_id[TNUM];
    int status;
    int i;
    clock_t start, end;

    status = pthread_mutex_init(&mutx, NULL);

    start = clock();

    for(i=0; i<TNUM; i++)
    {
        thr_id[i] = pthread_create(&p_thread[i], NULL, t_function, NULL);
        if(thr_id[i] < 0)
        {
            perror("thread create error: ");
            exit(i);
        }
    }

    for(i=0; i<TNUM; i++)
    {
        pthread_join(p_thread[i], (void**)&status);
    }

    end = clock();

    printf("time : %lf\n", (double)(end-start)/CLOCKS_PER_SEC);
    printf("result : %d\n", cnt);
    return 0;
}

当我在加入后打印“cnt”的值时,它有时会超过 1000,例如 1001 或 1002 ....

在我看来,虽然一个线程使 cnt 为 1000,但其他一些线程已经通过 while 条件获得互斥量并且该值超过最大值(1000)。

我认为只在 while 循环中添加检查代码是不好的方法。 有没有更好的方法来解决这个问题?

最佳答案

认为有 4 个线程正在等待获取互斥锁并同时运行。当他们到达 while(cnt < 1000) , 他们可能会也可能不会检查 cnt < 1000条件受制于操作系统。假设所有这些都满足,那么现在它们在 while 中并准备好获取锁并增加计数。

while(cnt < 1000)
{ 
    // --> assume that all threads are here
    pthread_mutex_lock(&mutx);
    cnt++;
    pthread_mutex_unlock(&mutx);
}

@编辑

感谢@Jonathan Leffler,为了得到正确的结果,改变它

while(cnt < 1000) { 
    pthread_mutex_lock(&mutx); 
    if (cnt < 1000)  
        cnt++; 
    pthread_mutex_unlock(&mutx); 
}

关于c - 如何控制互斥量的加锁和解锁?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49720718/

相关文章:

c - 结构内部 union

c - fcntl 的 F_GETLK 未返回锁定详细信息

multithreading - 线程互斥锁 : pthread_mutex_unlock() consumes lots of time

java - Java 中各种线程同步选项之间有什么区别?

将字节反转的 uint64_t 复制到 uint8_t 数组

c - mq_open() - EACCES,权限被拒绝

linux - 带 SSL 的 Linux 服务中的 .Net Core 2.2 API

linux - 预期整数表达式 -- linux

linux - 检查文件是否是从现在起 10 分钟后创建的

c - PRNG 在所有进程中返回相同的值