【发布时间】:2014-09-20 13:33:33
【问题描述】:
我很困惑如何使用 POSIX 来使用 Mutex。考虑以下代码:
void *print_message_function( void *ptr );
pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
main()
{
pthread_t thread1, thread2,thread3;
std::string message1 = "Apple";
std::string message2 = "Orange";
int iret1, iret2,iret3;
iret1 = pthread_create( &thread1, NULL, print_message_function, (void*) &message1);
iret2 = pthread_create( &thread2, NULL, print_message_function, (void*) &message1);
iret3 = pthread_create( &thread3, NULL, print_message_function, (void*) &message2);
pthread_join( thread1, NULL);
pthread_join( thread2, NULL);
pthread_join( thread3, NULL);
exit(EXIT_SUCCESS);
}
void *print_message_function( void *ptr )
{
pthread_mutex_lock( &count_mutex );
int i = 3 ;
while( i ) {
printf("i is %d ...%s \n", i,(*(std::string *)ptr).c_str() );
i-- ;
sleep (1) ;
}
pthread_mutex_unlock( &count_mutex );
}
线程 1 和线程 2 使用一个公共资源——message1。 Thread3 使用自己的资源——消息 3。 在 STDOUT 上搞乱打印对我来说是可以的。
程序的输出是
i is 3 ...Apple
i is 2 ...Apple
i is 1 ...Apple
i is 3 ...Apple
i is 2 ...Apple
i is 1 ...Apple
i is 3 ...Orange
i is 2 ...Orange
i is 1 ...Orange
正如我们所见,thread3 在最后执行。由于thread3不使用任何公共资源,我怎样才能让它“跳过互斥锁”。仅当两个线程访问同一块内存而不是其他情况时,如何才能启用互斥锁。互斥锁必须是动态的。我什至愿意指定一个变量,该变量不应指向内存中的相同位置以激活锁。 换句话说,我怎样才能创建一个只有在两个线程发生冲突时才被激活的互斥锁。
我知道这可能是一个重复的问题。但我无法找到任何解决这个问题的方法。另外,由于一些环境限制,我不能使用 C++11 STL 线程或 boost。我想要 pthreads 库的帮助。
【问题讨论】:
标签: c multithreading pthreads mutex