gpt4 book ai didi

c - pthread_mutex_lock 为什么不像往常一样阻塞线程

转载 作者:太空宇宙 更新时间:2023-11-04 03:30:25 27 4
gpt4 key购买 nike

最近看了一些关于thread mutex的代码,相关代码在这里:

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

pthread_mutex_t mutex;
pthread_cond_t cond;
pthread_t thread;

void fn(void *arg)
{
3 pthread_mutex_lock(&mutex);
printf( "signal before\n" );
4 pthread_cond_signal(&cond);
printf( "signal after\n" );
pthread_mutex_unlock(&mutex);
}
int main()
{
int err1;
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond,NULL);

1 pthread_mutex_lock(&mutex);
2 err1 = pthread_create(&thread, NULL, fn, NULL);
usleep(1);
pthread_cond_wait(&cond,&mutex);
printf( "main thread get signal\n");
pthread_mutex_unlock(&mutex);
pthread_join(thread, NULL);
pthread_mutex_destroy( &mutex );
pthread_cond_destroy( &cond );
}

在主线程中,首先我调用pthread_mutex_lock 函数锁定num 1 中的互斥量,然后在num 2 中创建子线程,并在子线程启动函数void fn( void *arg) 我又在num 3调用了pthread_mutex_lock,理论上应该会阻塞直到mutex(主线程)被释放,但是为什么它在子线程中还能继续执行num 4中的代码?

执行结果:

result_pic

gcc 版本

Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/usr/include/c++/4.2.1 Apple LLVM version 7.3.0 (clang-703.0.31) Target: x86_64-apple-darwin15.4.0 Thread model: posix InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin

非常感谢。

最佳答案

条件变量的目的是允许线程等待其他线程中发生的事情。使用互斥量执行此操作的问题是以下代码不起作用:

  1. 获取保护共享状态的锁。
  2. 看看我们是否需要等待,如果需要等待。

糟糕。现在我们在持有锁的同时等待。所以没有其他线程可以更改共享状态。所以我们会永远等待。让我们再试一次,这次释放锁:

  1. 获取保护共享状态的锁。
  2. 如果我们需要等待,释放锁并等待。

糟糕,我们还有问题。如果我们正在等待的事情发生在我们释放锁之后但在我们开始等待之前怎么办?再一次,我们将永远等待。

所以我们需要一个原子的“解锁并等待”功能来使第 2 步工作。这就是 pthread_cond_wait 的含义。因此在线程等待时互斥体被释放。

pthread_cond_wait 的规范用法是:

 pthread_mutex_lock(&mutex);
while (we_need_to_wait)
pthread_cond_wait(&cond, &mutex);
// possibly do some stuff while we still hold the mutex
pthread_mutex_unlock(&mutex);

请注意,这允许我们决定在我们仍然持有互斥量时等待,在不持有互斥量的情况下等待,但没有释放互斥量但我们尚未等待的竞争条件的窗口。

顺便说一句,以任何其他方式正确使用条件变量是极其困难的。因此,在您对条件变量的工作原理有深入的了解之前,您真的不应该尝试在任何其他模式中使用 pthread_cond_wait。绝对确保您始终准确地知道您在等待什么,并且您正在等待的东西受到您传递给 pthread_cond_wait 的互斥锁的保护。

关于c - pthread_mutex_lock 为什么不像往常一样阻塞线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37128905/

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