pthread_mutex_t和pthread_cond_t.app
爲何互斥鎖和條件鎖一般要一塊兒使用?.net
目的是給資源或者臨界區加鎖,同時不消耗CPU資源。code
若是沒有條件鎖,互斥鎖會一直輪詢,致使大量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; }