虚位以待(AD)
虚位以待(AD)
首页 > 脚本专栏 > linux shell > Linux中多线程详解及简单实例

Linux中多线程详解及简单实例
类别:linux shell   作者:码皇   来源:互联网   点击:

这篇文章主要介绍了Linux中多线程详解及简单实例的相关资料,这里对线程概念及优缺点做了详细介绍并说明如何创建和应用,需要的朋友可以参考下

Linux中多线程详解及简单实例

1.概念

进程:运行中的程序。

线程:一个程序中的多个执行路径。更准确的定义是:线程是一个进程内部的一个控制序列。

2.为什么要有线程?

用fork调用进程代价太高,需要让一个进程同时做多件事情,线程就非常有用。

3.线程的优点和缺点。

优点:

(1)有时,让程序看起来是在同时做两件事是非常有用的。 比如在编辑文档时,还能统计文档里的单词个数。
(2)一个混杂着输入、计算、输出的程序,利用线程可以将这3个部 分分成3个线程来执行,从而改变程序执行的性能。
(3)一般来说,线程之间切换需要操作系统所做的工作比进程间切换需要的代价小。

缺点:

(1)编写线程需要非常仔细的设计。
(2)对多线程的调试困难程度比单线程调试大得多。

4.创建线程

    #include <pthread.h>(1)int pthread_create(pthread_t *thread,pthread_attr_t *attr,void *(*start_routine)(void *),void *arg);
    pthread_t pthread_self(void);
    (2)int pthread_equal(pthread_t thread1,pthread_t thread2);
    (3)int 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 WorldWaiting for thread to finish...Thread joined, it returned Thank you for your CPU time!Message is now Bye!

以上就是Linux 多线程的实例详解,如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

相关热词搜索: Linux 多线程 Linux 多线程详解 Linux 多线