C/C++多线程与互斥锁
void * thread ( void * id) {
printf ( "this is a new thread, thread ID is %u\n" , pthread_self ( ) ) ;
return NULL ;
}
#include <unistd.h>
#include <sys/syscall.h>
#define gettid() syscall(__NR_gettid)
pthread_mutex_t mutex;
pthread_mutex_init ( & mutex, NULL ) ;
pthread_mutex_lock ( & mutex) ;
pthread_mutex_unlock ( & mutex) ;
pthread_mutex_destroy ( & mutex) ;
pthread_mutex_lock ( mutex) ;
while ( 条件不成立)
{
pthread_cond_wait ( cond, mutex) ;
}
. . .
pthread_mutex_unlock ( mutex) ;
pthread_cond_signal ( pthread_cond_t * cond) ;
pthread_cond_broadcast ( pthread_cond_t * cond) ;
pthread_cond_timedwait ( pthread_cond_t * cond, pthread_mutex_t * mutex, struct timespec * time) ;
条件锁与互斥锁应用:
pthread_mutex_lock ( & m_mutex) ;
pthread_cond_wait ( & m_cond, & m_mutex) ;
pthread_mutex_unlock ( & m_mutex) ;
pthread_mutex_lock ( & m_mutex) ;
pthread_cond_signal ( & m_cond) ;
pthread_mutex_unlock ( & m_mutex) ;
spin_lock_init ( spinlock_t * x) ;
spin_lock ( x) ;
spin_trylock ( x) ;
spin_unlock ( x) ;
spin_is_locked ( x) ;
pthread_rwlock_t rwlock;
int data= 1 ;
void readerA ( ) {
while ( 1 ) {
pthread_rwlock_rdlock ( & rwlock) ;
printf ( "A读者读出:%d\n" , data) ;
pthread_rwlock_unlock ( & rwlock) ;
Sleep ( 1000 ) ;
}
}
void writerB ( ) {
while ( 1 ) {
pthread_rwlock_wrlock ( & rwlock) ;
data++ ;
printf ( "B作者写入:%d\n" , data) ;
pthread_rwlock_unlock ( & rwlock) ;
Sleep ( 1000 ) ;
}
}
int main ( )
{
pthread_t t1;
pthread_t t2;
pthread_rwlock_init ( & rwlock, NULL ) ;
pthread_create ( & t1, NULL , readerA, NULL ) ;
pthread_create ( & t2, NULL , writerB, NULL ) ;
pthread_join ( t1, NULL ) ;
pthread_join ( t2, NULL ) ;
pthread_rwlock_destroy ( & rwlock) ;
return 0 ;
}
C++多线程互斥锁:
#include <thread>
#include <mutex>
#include <iostream>
int g_i = 0 ;
std: : mutex g_i_mutex;
void safe_increment ( )
{
std: : lock_guard< std: : mutex> lock ( g_i_mutex) ;
++ g_i;
std: : cout << std: : this_thread: : get_id ( ) << ": " << g_i << '\n' ;
}
int main ( )
{
std: : cout << "main: " << g_i << '\n' ;
std: : thread t1 ( safe_increment) ;
std: : thread t2 ( safe_increment) ;
t1. join ( ) ;
t2. join ( ) ;
std: : cout << "main: " << g_i << '\n' ;
}