各位看官们,大家好,上一回中咱们说的是线程创建与结束的例子,这一回咱们继续说该例子。闲话休提,言归正转。让我们一起talk C栗子吧!
看官们,我们在上一回中介绍了线程相关函数的用法,这一回中,我们将使用具体的实例来说明如果使用这些函数来操作线程。
下面是详细的操作步骤:
- 1.定义并且实现线程执行的函数,在该函数中使用pthread_exit函数结束线程;
- 2.在当前进程中使用pthread_create函数创建线程;
- 3.在当前进程中使用pthread_join函数等待线程结束,并且获取线程结束时的状态;
看官们,正文中就不写代码了,详细的代码放到了我的资源中,大家可以点击这里下载使用。
在程序中,当前的进程是主函数main所在的进程,当前的线程就是我们在main函数中使用pthread_create函数创建线程。
在代码中我们定义了两个全局变量:
- 一个用来保存线程函数的状态;
- 一个是线程函数的参数;
int status;
char param[] = "Thread function param";
我们在线程函数中修改了线程函数的状态,把它从初始值0修改成3.下面是线程函数的具体代码:
void *thread_func(void *param)
{
printf("this is the function,it is running normally .");
printf("and the param is: %s \n",(char *)param);
printf("The old status is %d \n",status);
status = 3; // change the status;
pthread_exit(&status); // end the thread
}
下面是程序的运行结果,请大家参考:
Create a thread
this is the function,it is running normally .and the param is: Thread function param
The old status is 0
thread function running finished and the status is :3 //在线程函数中修改了状态值
各位看官,关于线程创建与结束的例子咱们就说到这里。欲知后面还有什么例子,且听下回分解 。