读者写者问题
https://www.cnblogs.com/xybaby/p/6559212.html
同一进程中的线程究竟共享哪些资源
https://blog.youkuaiyun.com/q_l_s/article/details/51789245
https://blog.youkuaiyun.com/sinat_21026543/article/details/81912378
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
static int *ptr_num_of_a = NULL;
static int *ptr_num_of_b = NULL;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void* thread_function_a(void *arg) {
int n = 10;
pthread_mutex_lock(&mutex);
ptr_num_of_a = &n;
ptr_num_of_b = (int*)malloc(4);
*ptr_num_of_b = 3;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
pthread_mutex_lock(&mutex);
while (ptr_num_of_a) {
pthread_cond_wait(&cond, &mutex);
}
pthread_mutex_unlock(&mutex);
printf("thread a:n is %d\n", n);
printf("thread a:ptr_num_of_b is %d\n", *ptr_num_of_b);
return NULL;
}
void* thread_function_b(void *arg) {
pthread_mutex_lock(&mutex);
while (ptr_num_of_a == NULL) {
pthread_cond_wait(&cond, &mutex);
}
printf("thread b:n is %d\n", *ptr_num_of_a);
++ (*ptr_num_of_a);
ptr_num_of_a = NULL;
printf("thread b:ptr_num_of_b is %d\n", *ptr_num_of_b);
*ptr_num_of_b = 6;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
return NULL;
}
int main(int argc, char* const argv[]) {
pthread_t tid_a, tid_b;
pthread_create(&tid_a, NULL, thread_function_a, NULL);
pthread_create(&tid_b, NULL, thread_function_b, NULL);
pthread_join(tid_a, NULL);
pthread_join(tid_b, NULL);
return 0;
}
同一进程间的线程共享的资源有
1.堆
2.全局变量,静态变量
3.文件设备资源等
4.进程的代码段,打开的文件描述符,进程的当前目录。
独享的有
1.栈
2.寄存器,程序计数器pc
3.线程id,线程优先级
4.错误返回码