博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
pthread_create Linux函数 线程创建
阅读量:4283 次
发布时间:2019-05-27

本文共 1483 字,大约阅读时间需要 4 分钟。

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

线程它允许一个进程执行一个或多个执行路径(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

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

转载地址:http://jpngi.baihongyu.com/

你可能感兴趣的文章
How to pass macro definition from “makefile” command line arguments to C source code?
查看>>
英文句型
查看>>
mtd and /dev/mtd*相關資料
查看>>
cp: cannot create symbolic link to fat format of usb: Operation not permitted
查看>>
MTD bad Block issue
查看>>
How to change network interface name
查看>>
ubifs and ubi and mtd
查看>>
shell script set 用法
查看>>
英文序數寫法與唸法 Ordinal Numbers(轉載)
查看>>
DVB-S info
查看>>
绿盟扫描操作指导
查看>>
理解链路本地址与站点本地地址
查看>>
/proc/mtd 各个参数含义 -- linux内核
查看>>
linux nand flash常用命令
查看>>
NESSUS扫描操作指导
查看>>
C语言读取文件大小,载入文件全部内容
查看>>
C语言 static静态变量的作用
查看>>
Linux(C/C++)下的文件操作open、fopen与freopen
查看>>
C语言 文件操作的头文件
查看>>
C语言的常用库函数(dos)之四(dir.h文件下的一些函数)
查看>>