#include<iostream>
#include<sys/types.h>
#include<stdlib.h>
#include<pthread.h>
#include<unistd.h>
#include<string.h>
using namespace std;
int num=0;
void *thread_function1(void *arg)
{
cout<<"Thread 1 is running! The global variable is "<<*((int *)arg)<<endl;
cout<<"Let thread 1 change it to 1"<<endl;
*((int *)arg)=1;
}
int main()
{
cout<<"Main thread is running.The global variable is "<<num<<endl;
pthread_t thread;
int id;
id=pthread_create(&thread,NULL,thread_function1,(void *)(&num));
if(0!=id)
{
cout<<"Thread creation failed!"<<endl;
exit(EXIT_FAILURE);
}
sleep(10);
cout<<"Main thread is going on! The global ivariable is "<<num<<endl;
exit(0);
}
1.编译时首先定义宏_REENTRANT。程序只是为了验证功能,不能作为最后的产品代码。此测试程序也没有一定的命名规范,Just for learning!
2.执行结果为:
本文通过一个简单的C++程序示例展示了如何使用多线程来修改全局变量,并观察主线程与子线程间的数据变化。该示例有助于理解线程间的同步问题。

被折叠的 条评论
为什么被折叠?



