线程学习

来源:互联网 发布:部落冲突数据大全2017 编辑:程序博客网 时间:2024/04/28 23:35

1、创建线程

int pthread_create(pthread_t *tidp,const pthread_attr_t *attr,
(void*)(*start_rtn)(void*),void *arg);

头文件#include<pthread.h>


返回值:若线程创建成功,则返回0.若线程创建失败,则返回出错编号,

返回成功时,由tidp指向的内存单元被设置为新创建线程的线程ID。attr参数用于指定各种不同的线程属性。新创建的线程从start_rtn函数的地址开始运行,该函数只有一个万能指针参数arg,如果需要向start_rtn函数传递的参数不止一个,那么需要把这些参数放到一个结构中,然后把这个结构的地址作为arg的参数传入。

参数

第一个参数为指向线程标识符的指针。
第二个参数用来设置线程属性。
第三个参数是线程运行函数的起始地址。
最后一个参数是运行函数的参数。
因为pthread并非Linux系统的默认库,而是POSIX线程库。在Linux中将其作为一个库来使用,因此加上 -lpthread(或-pthread)以显式链接该库。(gcc -o example example.c -lpthread)运行./example

#include<stdio.h>

#include<stdlib.h>

#include<unistd.h>

#include<pthread.h>

#include<errno.h>

void thread(){printf("enter\n");int i;for(i=0;i<2;i++){printf("this is %d pthread\n",i);sleep(1);}}int main(void){pthread_t thid;int ret=0;ret=pthread_create(&thid,NULL,(void*)thread,NULL);if(ret!=0){perror("pthread_create");exit(1);}printf("this is main\n");return 0;}

所得结果与所期望的不同,出现此问题的原因是主线程没有等待子线程正常退出,主线程运行结束退出时,所有的子线程都退出了。要通过pthread_join函数等待子线程运行结束。

函数pthread_join用来等待一个线程的结束。头文件 : #include <pthread.h>

函数定义: int pthread_join(pthread_t thread, void **retval);
描述 :pthread_join()函数,以阻塞的方式等待thread指定的线程结束。当函数返回时,被等待线程的资源被收回。如果线程已经结束,那么该函数会立即返回。并且thread指定的线程必须是joinable的。
参数 :thread: 线程标识符,即线程ID,标识唯一线程。retval: 用户定义的指针,用来存储被等待线程的返回值。
返回值 : 0代表成功。 失败,返回的则是错误号。
#include<stdio.h>#include<stdlib.h>#include<unistd.h>#include<pthread.h>#include<errno.h>void thread(){printf("enter\n");int i;for(i=0;i<2;i++){printf("this is %d pthread\n",i);sleep(2);}}int main(void){pthread_t thid;int ret=0;ret=pthread_create(&thid,NULL,(void*)thread,NULL);if(ret!=0){perror("pthread_create");exit(1);}pthread_join(thid,NULL);printf("this is main\n");return 0;}


getpid()

函数原型:pid_t getpid(void);

功能:取得目前进程的进程ID

返回值:目前进程的进程ID

头文件:#include<unistd.h>

pthread_self()

头文件:#include<pthread.h>

原型:pthread_t pthread_self(void);

功能:获取线程自身的ID











0 0
原创粉丝点击