gpt4 book ai didi

c - 互斥锁不工作

转载 作者:太空宇宙 更新时间:2023-11-04 02:54:14 26 4
gpt4 key购买 nike

任何人都可以让我知道我的代码出了什么问题。我一次只希望一个线程访问临界区,但它们都进入了。

#include <stdio.h>
#include <unistd.h>
#include <pthread.h>

pthread_t th[5];
pthread_mutex_t mutex_for_some_value;
int value;

void * thread_talk(void * arguments) {

while (1) {

pthread_mutex_lock(&mutex_for_some_value);

printf("\n Now Accessed by %d", *((int*) arguments));

pthread_mutex_unlock(&mutex_for_some_value);
sleep(2);

printf("\n\n Thread %d is left critical section", *((int*) arguments));
}

return NULL;
}

int main(int argc, char **argv) {

int count[5] = { 1, 2, 3, 4, 5 };

printf("\n %d", pthread_mutex_init(&mutex_for_some_value, NULL));

for (int i = 0; i < 5; i++) {
printf("\n Creating %d thread", count[i]);
pthread_create(&th[i], NULL, &thread_talk, (void*) &count[i]);
}

for (int i = 0; i < 5; ++i) {
pthread_join(th[i], NULL);
}

pthread_mutex_destroy(&mutex_for_some_value);

printf("\n Main done");

return 0;
}

现在因为有互斥锁,所以没有两个线程应该进入我的临界区。但是输出是

0 创建 1 个线程

创建 2 个线程

创建 3 个线程

创建 4 个线程

创建 5 个线程

现在有 4 人访问

现在有 3 人访问

现在有 2 人访问

现在有 1 人访问

现在有 5 人访问

线程 4 处于临界区 现在有 4 人访问

线程 3 处于临界区 现在有 3 人访问

线程 1 处于临界区 现在有 1 人访问

线程 2 处于临界区 现在由 2 访问

线程 5 处于临界区

最佳答案

行:

sleep(2)

将延迟“Thread X is left critical section”输出,直到另一个线程打印“Now Accessed by Y”。锁定应该仍然有效。

关于c - 互斥锁不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19312589/

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