线程的创建和运行

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);

   }

  1. 运行结果:

     

  2. 回答问题:Linux中线程是怎样创建和运行的?

答:通过函数pthread_create()来创建一个线程,如果该函数的返回值为0,则线程创建成功。在pthread_create()中第三个参数标识了线程开始运行的函数的初始位置,会跳转到运行函数的位置来运行线程中的程序。

(3)int pthread_create(pthread_t *thread,

pthread_attr_t *attr,

void* (*start_routine)(void *),

void *arg//指向传递给线程的参数

);

参数的作用分别是什么?

答:

第一个参数是指线程标识符的指针

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值