c 多线程,多进程 学习

#include<stdio.h>
#include<pthread.h>
#include<string.h>
#include<sys/types.h>
#include<unistd.h>

/*
int x = 0;

pthread_mutex_t tl;

void *thr_fn(void *arg)
{
    int a = 0;
    for (a = 0; a <= 500; a++)
    {
        pthread_mutex_lock(&tl);
        printf("fn1 locked\n");
        x += a;
        sleep(3);
        pthread_mutex_unlock(&tl);
        
        printf("fn1 unlock\n");
    }
    
    return (void *)0;
}

void *thr_fn2(void *arg)
{
    
    int a = 0;
    for (a = 501; a <= 1000; a++)
    {
        pthread_mutex_lock(&tl);
        printf("fn2 locked\n");
//        printf("fn2 do\n");
        x += a;
        sleep(1);
        
        pthread_mutex_unlock(&tl);
        printf("fn2 unlock\n");
    }
    
    pthread_exit(arg);
}

int main()
{
    pthread_mutex_init(&tl, NULL);
    
    pthread_t ntid;
    pthread_create(&ntid, NULL, thr_fn, NULL);
    
    pthread_t ntid2;
    pthread_create(&ntid2, NULL, thr_fn2, NULL);
    
    pthread_join(ntid, NULL);
    pthread_join(ntid2, NULL);
    
    printf("%d\n" , x);
    
    return 0;
}

*/



int main()
{
    int x = 1023;
    
    printf("main : %d\r\n", getpid());
    
    pid_t fork_return = fork();
    
    printf("fork_return = %d\r\n", fork_return);
    
    
    if(0 == fork_return)
    {
        printf("child : %d\r\n", getpid());
        
        sleep(1);
        
        printf("child : x = %d, %d\r\n", (int)&x, x);
        x += 1000;
        sleep(3);
        printf("child : x = %d\r\n", x);
    }
    else if(fork_return > 0)
    {
        printf("parent : %d\r\n", getpid());
        
        sleep(1);
        
        printf("parent : x = %d, %d\r\n", (int)&x, x);
        x += 10000;
        sleep(3);
        printf("parent : x = %d\r\n", x);
    }
    
    
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值