【问题标题】:Difference between mutex lock and pthread_join互斥锁和 pthread_join 的区别
【发布时间】:2011-08-28 13:07:35
【问题描述】:

两者有什么区别?

在执行另一个线程之前,它们都等待一个线程完成,这不是一回事吗?

我正在尝试理解以下代码

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

void *functionC();
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
int  counter = 0;

main()
{
    int rc1, rc2;
    pthread_t thread1, thread2;

 /*Create independent threads each of which will execute functionC */

     if( (rc1=pthread_create( &thread1, NULL, &functionC, NULL)) )
   {
      printf("Thread creation failed: %d\n", rc1);
   }

   if( (rc2=pthread_create( &thread2, NULL, &functionC, NULL)) )
   {
      printf("Thread creation failed: %d\n", rc2);
   }

   /* Wait till threads are complete before main continues. Unless we  */
   /* wait we run the risk of executing an exit which will terminate   */
   /* the process and all threads before the threads have completed.   */

   pthread_join( thread1, NULL);
   pthread_join( thread2, NULL);

   exit(0);
}    
void *functionC()
{
   pthread_mutex_lock( &mutex1 );
   counter++;
   printf("Counter value: %d\n",counter);
   pthread_mutex_unlock( &mutex1 );
}

谢谢。

【问题讨论】:

  • 它们并不是特别相似。这有点像问苹果和供给侧经济学有什么区别。

标签: c multithreading pthreads


【解决方案1】:

pthread_join() 等待线程退出。 mutex_lock 获得对信号量的控制,以防止协作线程同时访问受保护的资源。

【讨论】:

    【解决方案2】:

    它们实际上不是一回事。

    互斥量(互斥信号量)是一种将资源的使用限制为一次只限于一个线程的方法(两个线程显然都可以运行)。当线程从pthread_mutex_lock 调用成功返回时,保证它是唯一持有该锁的线程。在该点之后尝试锁定该互斥体的任何线程通常都必须等到拥有的线程解锁它。

    换句话说,拥有锁的线程是唯一能够操作受该锁保护的资源的线程(当然,假设其他线程在没有先获取锁的情况下不会接触资源 - 你必须玩按规则)。

    另一方面,pthread_join 允许一个线程等待另一个线程退出。 这通常用于主线程中等待所有子线程退出(有其他用途,这只是一个典型的用途)。从pthread_join 成功返回意味着其他线程不再运行。

    在您显示的代码中,两个线程同时运行,counter 增量和对printf 的调用都受到mutex1 的保护。在main 结束时的pthread_join 调用将使主线程等到您的两个子线程退出后再继续。

    顺便说一句,您应该检查来自pthread_mutex_lock 的返回值,因为它可能失败。在这种情况下,您不想继续修改受保护的资源,因为可能会发生损坏。 pthread_join 同上。

    而且,为了更全面的测试,以下功能会更好:

    void *functionC() {
        int i;
        for (i = 1000; i > 0; i--) {
            pthread_mutex_lock (&mutex1);
            counter++;
            printf ("Counter value: %d\n", counter);
            pthread_mutex_unlock (&mutex1);
        }
    }
    

    因为它更有可能让线程并行运行。如果没有循环,一个线程很有可能会在第二个线程开始之前退出。

    【讨论】:

    • ^ 你的意思是像那个线程使用的变量一样的资源?
    • @Ted,这就是一个例子。但是互斥锁可用于保护变量,防止代码同时在两个线程中运行,阻止向终端的输出被多个线程混合以及许多其他事情。
    • 除非实现为pthread_mutex_lock 定义了额外的错误条件,或者您使用了特殊的互斥锁类型(如错误检查或健壮),否则pthread_mutex_lock 不会失败。如果它因特定于实现的错误而失败,我不确定你如何处理这个问题。我认为除非使用健壮的互斥锁,否则不检查返回值是非常合理的。
    猜你喜欢
    • 1970-01-01
    • 2012-03-12
    • 2011-04-13
    • 2010-11-06
    • 1970-01-01
    • 2014-09-26
    • 2010-10-22
    • 2018-05-23
    • 2014-06-24
    相关资源
    最近更新 更多