线程 pthread_create Linux函数 线程创建

来源:互联网 发布:手机休眠关闭网络 编辑:程序博客网 时间:2024/04/30 10:40

线程:是在某个进程中被创建的,而它达到生命周期都在这个进程中。

线程它允许一个进程执行一个或多个执行路径(1个进程可以有多个线程,来执行不同的程序),这些执行路径由系统异步调度。

进程有自己的数据段,代码段,堆栈段。

而线程与进程的区别:

1.       代码段一样

2.数据段一样(全局变量)。

3.栈堆段不一样!!!!!

创建线程的函数:

#include<pthread.h>

int  pthread_create(pthread_t*thread,pthread_attr_t   *attr,

void * (*start_routine)(void *arg),

void *arg);

功能:创建线程

返回值:成功0

thread :程序的ID(标示符)。

attr:线程的属性设置,如果为NULL,则创建系统默认的线程属性。

start_routine:线程运行函数的起始地址。

最后一个参数是:线程运行函数的参数。

例子:

#include<stdio.h>

#include<pthread.h>

#include<stdlib.h>

void *thfun(void *arg)

{                    printf("new  thread!\n");

       printf("%s\n",(char*)arg);

        return ((void *)0);

}

int main(int argc ,char *argv[])

{

       int ret;

       pthread_t pthid;

       ret=pthread_create(&pthid,NULL,thfun,(void *)"hello");

      // 第一个参数为线程ID,把它保存在pthid中。

       //If attr is NULL, the default attributes shall be used.

       //第二个参数ifNULL,则创建默认属性的进程。

      // 。。。3。。线程运行函数的起始地址,

      //..... 4.... 线程运行函数的参数。

  If(ret!=1){

      perror("can'tcreat thread ");

exit(EXIT_FAILURE);

}  

       printf("main thread!\n");

        sleep(1);

       exit(0);//return 0;

}

 

 

运行结果:

下面我们看个例子:

#include<stdio.h>

#include<stdlib.h>

 #include<pthread.h>

void *th_fun(void*arg)

{

        printf("%s",arg);//打印传递的参数

        while(1)

                fputs("new thread \n",stdout);

//输出字符串new thread到标准输出

        return ((void*)0);

}

int main()

{

        int ret;

        pthread_t tid;

       if((ret=pthread_create(&tid,NULL,th_fun,"new thread  created!\n"))==-1)

        {

                perror("pthread_createerror ");

                exit(EXIT_FAILURE);

        }

        while(1)

                fputs("main  thread \n",stdout);

//输出字符串main  thread到标准输出

        return 0;

}

运行结果:

我们从运行结果来看,它一会输出main thread ,一会输出new thread

可以看出系统是对两个线程进行调度。

 

原创粉丝点击