Joh*_*ohn 5 c multithreading pthreads
这两者有什么区别?
它们是不是一样的,因为它们都在等待一个线程在执行另一个线程之前完成?
我正在尝试理解以下代码
#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 );
}
Run Code Online (Sandbox Code Playgroud)
谢谢.
pax*_*blo 10
他们实际上并不是一回事.
互斥(互斥信号量)是一种将资源的使用限制为一次一个线程的方法(两个线程显然都能够运行).当一个线程从一个pthread_mutex_lock调用成功返回时,它保证是唯一一个持有该锁的线程.尝试在该点之后锁定该互斥锁的任何线程通常必须等到拥有线程解锁它.
换句话说,具有锁的线程是唯一能够操纵受该锁保护的资源的线程(当然,假设其他线程在没有首先获取锁的情况下不接触资源 - 您必须遵守规则).
一pthread_join,在另一方面,允许一个线程等待另一个线程退出.这通常在主线程中用于等待所有子线程退出(还有其他用途,这只是一个典型的用法).成功返回pthread_join意味着另一个线程不再运行.
在您显示的代码中,两个线程同时运行,并且counter增量和调用printf都受到保护mutex1.最后的pthread_join调用main将使主线程等待,直到您的两个子线程退出,然后继续.
另外,您应该检查返回值,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);
}
}
Run Code Online (Sandbox Code Playgroud)
因为它更可能让线程并排运行.如果没有循环,一个线程很可能会在第二个线程开始之前退出.