pthread_mutex_t和pthread_cond_t.
为什么互斥锁和条件锁通常要一起使用?
目的是给资源或者临界区加锁,同时不消耗CPU资源。
如果没有条件锁,互斥锁会一直轮询,导致大量CPU时间被占用。如下代码中,如果将条件锁注掉,那么大约占18.5%的CPU时间,如果有条件锁,基本是0%。
/**
* @file: test_thread_mutex.c
* @brief : test whether pthread_mutex_t is enough in a multi-threaded application
*/
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <assert.h>
#define TOTAL_THREAD_NUM 10
pthread_mutex_t work_mutex;
pthread_cond_t work_cond;
int running[TOTAL_THREAD_NUM] = {0};
void *thread_function(void *arg);
static int check_collision() {
int i = 0;
int sum = 0;
for (i=0; i<TOTAL_THREAD_NUM; i++) {
sum += running[i];
}
if (sum > 1) {
return 1;
} else {
return 0;
}
}
int main(int argc, char *argv[]) {
pthread_t thread[TOTAL_THREAD_NUM];
int ret;
int i;
ret = pthread_mutex_init(&work_mutex, NULL);
if (ret != 0) {
perror("Mutex Initialization Failed");
exit(EXIT_FAILURE);
}
ret = pthread_cond_init(&work_cond, NULL);
if (ret != 0) {
perror("Cond Initialization Failed");
exit(EXIT_FAILURE);
}
for (i=0; i<TOTAL_THREAD_NUM; i++) {
printf("Main: creating thread %d \n", i);
ret = pthread_create(&thread[i], NULL, thread_function, (void*)i);
if (ret != 0) {
perror("Create Threads Failed");
exit(EXIT_FAILURE);
}
}
for (i=0; i<TOTAL_THREAD_NUM; i++) {
ret = pthread_join(thread[i], NULL);
if (ret != 0) {
perror("thread join failed");
exit(EXIT_FAILURE);
}
}
pthread_mutex_destroy(&work_mutex);
return 0;
}
void* thread_function(void *arg) {
int i = (int)arg;
for (;;) {
pthread_mutex_lock(&work_mutex);
/* printf("thread %d is running now\n", i); */
/* fflush(stdout); */
pthread_cond_wait(&work_cond, &work_mutex);
running[i] = 1;
if (check_collision() != 0) {
printf("Collision Occured!\n");
}
running[i] = 0;
pthread_cond_signal(&work_cond);
pthread_mutex_unlock(&work_mutex);
}
return NULL;
}