在多线程程序中,经常要用全局变量来实现多个函数间的数据共享。由于数据空间是共享的,因此全局变量也为所有线程共有。
测试代码如下:
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
int key = 100; //全局变量
void *helloworld_one(void *arg)
{
printf("the message is %s\n",(char *)arg);
key = 10;
printf("key=%d, the child id is %lu\n", key, pthread_self());
return NULL;
}
void *helloworld_two(void *arg)
{
printf("the message is %s\n", (char *)arg);
sleep(1);
printf("key=%d, the child id is %lu\n", key, pthread_self());
return NULL;
}
int main(int argc, char *argv[])
{
pthread_t thread_id_one;
pthread_t thread_id_two;
//创建线程
pthread_create(&thread_id_one, NULL, helloworld_one, "helloworld_one");
pthread_create(&thread_id_two, NULL, helloworld_two, "hellowor