Linux中多线程

1.概念
进程:运行中的程序。
线程:一个程序中的多个执行路径。更准确的定义是:线程是一个进程内部的一个控制序列。
2.为什么要有线程?
用fork调用进程代价太高,需要让一个进程同时做多件事情,线程就非常有用。
3.线程的优点和缺点。
优点:
(1)有时,让程序看起来是在同时做两件事是非常有用的。 比如在编辑文档时,还能统计文档里的单词个数。
(2)一个混杂着输入、计算、输出的程序,利用线程可以将这3个部 分分成3个线程来执行,从而改变程序执行的性能。
(3)一般来说,线程之间切换需要操作系统所做的工作比进程间切换需要的代价小。
缺点:
(1)编写线程需要非常仔细的设计。
(2)对多线程的调试困难程度比单线程调试大得多。
4.创建线程

#include <pthread.h>1int pthread_create(pthread_t *thread,pthread_attr_t *attr,void *(*start_routine)(void *),void *arg);
pthread_t pthread_self(void);
(2int pthread_equal(pthread_t thread1,pthread_t thread2);
(3int pthread_once(pthread_once_t *once_control,void(*init_routine)(void));

linux系统支持POSIX多线程接口,称为pthread。编写linux下的多线程程序,需要包含头文件pthread.h,链接时需要使用库libpthread.a
如果在主线程里面创建线程,程序就会在创建线程的地方产生分支,变成两个部分执行。线程的创建通过函数pthread_create来完成。成功返回0。
1.线程创建:
int pthread_create(pthread_t thread,pthread_attr_t *attr,void (start_routine)(void ),void *arg);
pthread_t pthread_self(void);
参数说明:
thread:指向pthread_create类型的指针,用于引用新创建的线程。
attr:用于设置线程的属性,一般不需要特殊的属性,所以可以简单地设置为NULL。
start_routine)(void ):传递新线程所要执行的函数地址。
arg:新线程所要执行的函数的参数。
调用如果成功,则返回值是0,如果失败则返回错误代码。
2.线程终止
void pthread_exit(void *retval);
参数说明:
retval:返回指针,指向线程向要返回的某个对象。
线程通过调用pthread_exit函数终止执行,并返回一个指向某对象的指针。注意:绝不能用它返回一个指向局部变量的指针,因为线程调用该函数后,这个局部变量就不存在了,这将引起严重的程序漏洞。
3.线程同步
int pthread_join(pthread_t th, void **thread_return);
参数说明:
th:将要等待的线程,线程通过pthread_create返回的标识符来指定。
thread_return:一个指针,指向另一个指针,而后者指向线程的返回值。
一个简单的创建多线程的程序:

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void *thread_function(void *arg);

char message[] = "Hello World";

int main()
{
    int res;
    pthread_t a_thread;
    void *thread_result;

    res = pthread_create(&a_thread, NULL, thread_function, (void *)message);
    if (res != 0)
    {
        perror("Thread creation failed!");
        exit(EXIT_FAILURE);
    }

    printf("Waiting for thread to finish.../n");

    res = pthread_join(a_thread, &thread_result);
    if (res != 0)
    {
        perror("Thread join failed!/n");
        exit(EXIT_FAILURE);
    }

    printf("Thread joined, it returned %s/n", (char *)thread_result);
    printf("Message is now %s/n", message);

    exit(EXIT_FAILURE);
}

void *thread_function(void *arg)
{
    printf("thread_function is running. Argument was %s/n", (char *)arg);
    sleep(3);
    strcpy(message, "Bye!");
    pthread_exit("Thank you for your CPU time!");
}

输出结果

$./thread1[输出]:
thread_function is running. Argument was Hello World
Waiting for thread to finish...
Thread joined, it returned Thank you for your CPU time!
Message is now Bye!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值