最简单的linux线程创建、共享变量

#include 
#include 
#include 
#include 
#include 
#include 

static int SharedData = 4;//在线程中改变共享变量

void * create(void *arg)
{
    printf("new pthread...\n");
    printf("shard data = %d \n",SharedData);
    SharedData++;
    return (void*)(0);
}

main()
{
    pthread_t tid;//线程号
    printf("Thread is being created...\n");
    int Status = pthread_create(&tid,NULL,create,NULL);
    if(Status != 0)
    {
        printf("Thread creation failed.\n");
        exit(EXIT_FAILURE);
    }
    printf("Main pid is %d\n",getpid());//获取进程ID
    sleep(1);//进程睡眠一秒钟
    if(SharedData != 4)
    {
        printf("SharedData is changed to %d\n",SharedData);
    }
    printf("Main pid is %d\n",getpid());
    exit(EXIT_SUCCESS);
}

输出

Main pid is 5564
new pthread...
shard data = 4 
SharedData is changed to 5
Main pid is 5564


你可能感兴趣的:(linux)