作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
<分区>
我有一个关于基本互斥锁和解锁示例的问题!
#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 循环中添加检查代码是不好的方法。有没有更好的方法来解决这个问题?
为什么 pickle 重用现有的 Python 类“C”而不是从 pickle 字节重建类?有没有一种方法可以在没有副作用的情况下 pickle 和解 pickle ? 这是我的回复 session
我是一名优秀的程序员,十分优秀!