线程与进程资源共享独享

读者写者问题

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.错误返回码

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值