c 多线程,多进程 学习

来源:互联网 发布:mac一般用什么办公软件 编辑:程序博客网 时间:2024/05/22 17:32
#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;}

0 0