linux多线程学习笔记二---基本线程编程

来源:互联网 发布:开淘宝店在还好做吗 编辑:程序博客网 时间:2024/06/11 17:29
一,线程常见函数介绍
#include<stdio.h>#include<pthread.h>void *thread_routine(void *arg){pthread_t tid=pthread_self();printf("thread 1 say hello\n");return arg;}int main(){pthread_t thread_id;void * thread_result;int status;status=pthread_create(&thread_id,NULL,thread_routine,NULL);if(status!=0){printf("create error\n");return 1;}status=pthread_join(thread_id,&thread_result);if(status!=0){printf("join error\n");return 1;}if(thread_result==NULL)return 0;elsereturn 1;}
首先看上面这个例子,简单的创建一个线程,在线程中打印thread 1 say hello。
首先分析上面程序涉及的函数。
1,创建线程,线程通过调用pthread_create函数来创建其他线程,原型如下:
#include <pthread.h>typedef void*(func)(void*);int pthread_create(pthread_t *tid, const pthread_attr_t *attr,func *f, void *arg);      若成功返回0,若出错则非0
当pthread_create返回时,参数tid包含新创建线程的ID,新线程可以通过pthread_self函数获取自己线程的ID。
#include <pthread.h>
pthread_t pthread_self();  
2,回收终止线程的资源
线程通过调用pthread_join函数等待其他线程终止
#include <pthread.h>int pthread_join(pthread_t tid,void **thread_retrun);  若成功返回0,出错则非零
pthread_join函数会阻塞,直到线程tid终止,然后回收已终止线程占用的所有存储器资源。
除此还要熟悉一下几个函数
#include <pthread.h>int pthread_detach(pthread_t tid); 
int pthread_exit(void*thread_return);
int pthread_cancel(pthread_t);  

pthread_detach()函数用于指示应用程序在线程tid终止时回收其存储空间。如果tid尚未终止,pthread_detach()不会终止该线程。

一个线程是以一下方式之一来终止的:当顶层的线程例程返回时,线程会隐式的终止;通过调养pthread_exit函数显式的终止,该函数返回一个指向thread_return的指针。如果主线程调用pthread_exit,它会等待所有其他对等线程终止,然后再终止主线程和整个进程,返回值为thread_return。对等线程也可以调用pthread_cancel来终止当前线程。

二,线程的生命周期

通常将线程的状态分为以下几种:就绪,运行,阻塞,终止,状态转移图如下所示。

线程的创建,上例中status=pthread_create(&thread_id,NULL,thread_routine,NULL);完成线程的创建工作,线程创建注意:pthread_create函数返回同线程执行之间没有同步关系,被创建之后进入就绪状态。线程启动,即开始执行pthread_routine函数。通常线程在以下情况被阻塞:试图加锁一个已经锁住的互斥量;等待某个条件变量;执行无法立即完成的I/O操作。程序中pthread_join函数处阻塞,等待它创建的线程结束。线程终止,本例中线程pthread_routine线程资源在pthread_join函数返回时被回收。而pthread_detach分离的线程在线程结束时自动被回收。