1.实验目的
(1)全面理解Iinux线程的运行机制,掌握编写线程的方法
(2)理解同步机制的作用,掌握解决该问题的算法思想,正确使用同步机制。
(3)学习使用Linux线程同步机制解决互斥和同步问题。
2.实验环境
已安装Linux操作系统的微机一台
3.参考资料《Linux C一站式学习》
4.实验内容
一、Linux中线程的创建和运行
在主函数中创建一个线程,其功能是循环输出3次“This is the second pthread.”;主线程也循环输出3次“This is the main pthread.”,观察并分析它们的执行过程。注意编译时使用-lpthread选项,比如命令gcc –o pthread pthread.c -lpthread
源程序清单,文件名:pthread.c
#include <stdio.h>
#include <pthread.h> //线程所用头函数
/*定义线程的执行函数*/
void thread(void) //必须使用void作为返回类型
{
int i;
for(i=0;i<3;i++)
{
printf(“This is the second pthread.\n”);
//显示自己是子线程
sleep(1);
}
}
main()
{ /*定义线程内部标识 */
pthread_t threadid;
int i,ret;
/*创建一个子线程并指定执行函数,函数不带参数*/
ret=pthread_create(&threadid,NULL,(void*)thread,NULL);
if(ret!=0)
{ printf ("Create pthread error!\n");
exit (1);}
/*主线程循环输出3次*/
pthread_join(threadid,NULL); //等待子线程结束
for(i=0;i<3;i++)
{
printf("This is the main pthread.\n");
sleep(1);
} exit(0);
}
- 运行结果:
- 回答问题:Linux中线程是怎样创建和运行的?
答:通过函数pthread_create()来创建一个线程,如果该函数的返回值为0,则线程创建成功。在pthread_create()中第三个参数标识了线程开始运行的函数的初始位置,会跳转到运行函数的位置来运行线程中的程序。
(3)int pthread_create(pthread_t *thread,
pthread_attr_t *attr,
void* (*start_routine)(void *),
void *arg//指向传递给线程的参数
);
参数的作用分别是什么?
答:
第一个参数是指线程标识符的指针