一、多线程基本概念
1. 线程的基本概念
① 线程就是轻量级的进程
②线程和创建他的进程共享代码段、数据段
③线程拥有自己的栈
2. 在实际应用中,多个线程往往会访问同一数据或资源,为避免线程之间相互影响,需要引入互斥机制,而互斥锁(mutex)是互斥机制中的一种
3. 简单实例
#include <stdio.h> #include <pthread.h> pthread_t work1Id; pthread_t work2Id; int work1Ret = 1; int work2Ret = 2; pthread_mutex_t mutex; int number = 0; void* Work1(void* args) { int i = 0; printf("I am work%d ", *((int*)args)); for(i = 0; i < 10; i++) { pthread_mutex_lock(&mutex); number++; pthread_mutex_unlock(&mutex); printf("I am work%d, number = %d ", *((int*)args), number); sleep(1); } return &work1Ret; } void* Work2(void* args) { int i = 0; printf("I am work%d ", *((int*)args)); for(i = 0; i < 10; i++) { pthread_mutex_lock(&mutex); number++; pthread_mutex_unlock(&mutex); printf("I am work%d, number = %d ", *((int*)args), number); sleep(1); } return &work2Ret; } int main() { int args1 = 1; int args2 = 2; void* work1Ret = NULL; void* work2Ret = NULL; pthread_mutex_init(&mutex, NULL); pthread_create(&work1Id, NULL, Work1, &args1); pthread_create(&work2Id, NULL, Work2, &args2); pthread_join(work1Id, &work1Ret); if(work1Ret != NULL) { printf("work1Ret = %d ", *((int*)work1Ret)); } pthread_join(work2Id, &work2Ret); if(work2Ret != NULL) { printf("work2Ret = %d ", *((int*)work2Ret)); } return 0; }
二、线程同步
1. 多个线程按照规定的顺序来执行,即为线程同步。
2. 条件变量
①初始化
pthread_cond_t cond_ready = PTHREAD_COND_INITIALIZER;
②等待条件成熟
pthread_wait(&cond_ready, &mutex); //会对mutex先进行解锁操作
③设置成熟条件
pthread_cond_signal(&cond_ready)
3. 简单实例
#include <stdio.h> #include <pthread.h> pthread_t work1Id; pthread_t work2Id; int work1Ret = 1; int work2Ret = 2; pthread_cond_t cond_ready = PTHREAD_COND_INITIALIZER; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int number = 0; void* Work1(void* args) { int i = 0; printf("I am work%d ", *((int*)args)); for(i = 0; i < 10; i++) { pthread_mutex_lock(&mutex); number++; if(number >= 10) { printf("I am work%d, Finish ", *((int*)args)); pthread_cond_signal(&cond_ready); } pthread_mutex_unlock(&mutex); printf("I am work%d, number = %d ", *((int*)args), number); sleep(1); } return &work1Ret; } void* Work2(void* args) { printf("I am work%d ", *((int*)args)); pthread_mutex_lock(&mutex); if(number <= 10) { pthread_cond_wait(&cond_ready, &mutex); printf("I am work%d, number = %d ", *((int*)args), number); } return &work2Ret; } int main() { int args1 = 1; int args2 = 2; void* work1Ret = NULL; void* work2Ret = NULL; pthread_create(&work1Id, NULL, Work1, &args1); pthread_create(&work2Id, NULL, Work2, &args2); pthread_join(work1Id, &work1Ret); if(work1Ret != NULL) { printf("work1Ret = %d ", *((int*)work1Ret)); } pthread_join(work2Id, &work2Ret); if(work2Ret != NULL) { printf("work2Ret = %d ", *((int*)work2Ret)); } return 0; }