gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:03:48 25 4
gpt4 key购买 nike

<分区>

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

#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 循环中添加检查代码是不好的方法。有没有更好的方法来解决这个问题?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com