线程

来源:互联网 发布:专业麦克风 知乎 编辑:程序博客网 时间:2024/06/06 03:36

线程

1.       线程的基本概念

线程是存在于一个进程中的更小的执行单元,一个进程之下可以有多个线程,且同一进程下的线程共享进程的所有资源。

2.       线程的创建

在linux环境下,一般用POSIX标准的线程函数,包含在头文件<pthread.h>,可以调用pthread_create()函数创建一个进程,下面是一个程序实例,来自《Advanced Linux programming》

////  main.c//  thread////  Created by busyfisher on 13-4-23.//  Copyright (c) 2013年 busyfisher. All rights reserved.//#include <stdio.h>#include <pthread.h>void* print_xs(void *unused){    while(1)        fputc('x',stderr);    return NULL;}int main(int argc, const char * argv[]){    pthread_t thread_id;    pthread_create(&thread_id,NULL,&print_xs,NULL);    while(1)        fputc('o',stderr);    return 0;}
运行结果:交替输出‘O’和‘x’
pthread_create()接受4个参数,第一个参数是线程号,第二个指针指向线程的属性,如果为空,表示线程为默认属性,第三个参数是函数指针,第四个是传递给执行函数的参数

3.   向线程传递参数

代码实例:

////  main.c//  thread////  Created by busyfisher on 13-4-23.//  Copyright (c) 2013年 busyfisher. All rights reserved.//#include <stdio.h>#include <pthread.h>void* print_xs(void *unused){    char *c = (char* )unused;    while(1)        fputc((*c),stderr);    return NULL;}int main(int argc, const char * argv[]){    pthread_t thread_id;    char t = 's';    pthread_create(&thread_id,NULL,&print_xs,&t);//向线程传递一个打印字符    while(1)        fputc('o',stderr);    return 0;}
运行结果:交替输出‘s’和'o'

但是该程序存在一个BUG,当主函数退出时,子线程仍然会访问t所在的位置,所以需要让主函数等待所有的线程退出后再退出,为了解决这个问题,我们可以调用pthread_join()函数:pthread_join(&thread_id,NULL)。所以在设计多线程程序时,需要注意线程所用到的变量是否会被其它线程析构。对于pthread_join()函数,第一个参数表示线程的ID,第二个参数可以用于接收线程的返回值。

4  异步线程和同步线程