linux编程---线程

来源:互联网 发布:网络营销策划案对象 编辑:程序博客网 时间:2024/05/16 17:35
线程

线程是进程中的一个独立控制流,由环境(包括寄存器集和程序计数器)和一系列要执行的指令组成。
所有进程至少由一个线程组成。所有线程共享为该进程分配的公共空间。

线程基本上不拥有系统资源,只拥有少量在运行中必不可少的资源(如程序计数器、
一组寄存器、栈、线程信号掩码、局部线程变量和线程私有数据),但是它可与同属一个进程
的其他线程共享进程所拥有的全部资源(同一地址空间、通信的信号处理机制、数据与I/O。

创建线程

#include <pthread.h>

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                   void *(*start_routine) (void *), void *arg);

线程退出与等待

线程退出操作
新创建的线程从执行用户定义的函数处开始执行,直到出现以下情况时退出:
调用pthread_exit函数退出。
调用pthread_cancel函数取消该线程
创建线程的进程退出或者整个函数结束
其中的一个线程执行了exec类函数执行新的进程

void pthread_exit(void *retval);

等待线程
为了有效回收子线程资源,在主线程中都将等待子线程结束,显示的等待某线程结束
可以调用pthread_join函数,其类似于进程的wait函数。
 int pthread_join(pthread_t thread, void **retval);
 
设置某个线程为独立线程,可以调用pthread_detach函数
int pthread_detach(pthread_t thread);

取消线程
int pthread_cancel(pthread_t thread);

简单示例
#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>

void *fchild1(char* argc)
{
        printf("child1 message is %s \n",argc);

        printf("child1 id is %u\n",pthread_self());
}

void *fchild2(char* argc)
{
        printf("child2 message is %s \n",argc);

        printf("child2 id is %u\n",pthread_self());
}

int main()
{
        pthread_t child1;
        pthread_t child2;

        pthread_create(&child1,NULL,(void*)*fchild1,"hello child1");
        pthread_create(&child2,NULL,(void*)*fchild2,"hello child2");

        pthread_join(child1,NULL);
        pthread_join(child2,NULL);

}

线程调度策略
(1)FIFO先入先出原则:首先请求服务的对象首先得到CPU的处理。
(2)最短作业优先原则:需要最小系统时间的服务首先得到处理。
(3)最高优先级优先原则:优先级最高的服务首先得到处理。
(4)时间轮片原则:每个任务分配一个系统时间片,轮流执行。