线程是一种轻量级的进程,与进程最大的不同是线程没有系统资源。线程是操作系统调度的最小单位,可以理解为一个进程是有一个或多个线程组成的。在操作系统内核中,是按照线程作为调度单位来调度资源的。
Linux 系统开发多线程程序大多使用者pthread 库,pthread 是符合 POSIX 线程标准的一个应用库,提供了线程的创建以及管理方法。
创建线程的函数为:
#include <pthread.h> int pthread_create(pthread_t *thread, // 新创建的线程ID const pthread_attr_t *attr, // 线程属性 void *(*start_routine) (void *), // 新创建的线程从start_routine开始执行 void *arg); // 执行函数的参数
取消线程的函数为:
#include <pthread.h> int pthread_cancel(pthread_t thread ); //要取消的线程ID
等待线程的函数:
#include <pthread.h> int pthread_join(pthread_t thread, // 等待退出的线程ID void **retval); // 获取线程退出时的返回值
linux 下创建多线程的例子
在主程序中创建两个线程 mid_thread和 term_thread ,mid线程不断等待term线程终止它,并且每隔2秒打印一次等待的次数。term线程接受从主函数传进来的mid线程的ID,如果线程ID合法,就调用 pthread_cancel()函数结束mid线程。
CODE如下;
#include <pthread.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> void* mid_thread(void *arg); void* term_thread(void *arg); int main(){ pthread_t mid_tid,term_tid; if (pthread_create(&mid_tid, NULL, mid_thread, NULL)){ perror("Create mid thread error!"); return 0; } if (pthread_create(&term_tid, NULL, term_thread, &mid_tid)){ perror("create term thread error"); return 0; } if (pthread_join(mid_tid, NULL)){ perror("wait mid thread error!"); return 0; } if (pthread_join(term_tid, NULL)){ perror("error"); return 0; } return 0; } void* mid_thread(void *arg){ int times = 0; printf("mid thread created!\n"); while(2){ printf("waiting term thread %d times!\n",times); sleep(1); times++; } } void* term_thread(void *arg){ pthread_t *tid; printf("term thread created!\n"); sleep(2); if(NULL != arg){ tid = arg; pthread_cancel(*tid); } }
编译
如果使用 gcc thread.c ,则会输出错误,即:
lixinxing@lixinxing-ideapad:~$ gcc pthread.c /tmp/cceVpg9m.o:在函数‘main’中: pthread.c:(.text+0x2e):对‘pthread_create’未定义的引用 pthread.c:(.text+0x63):对‘pthread_create’未定义的引用 pthread.c:(.text+0x89):对‘pthread_join’未定义的引用 pthread.c:(.text+0xaf):对‘pthread_join’未定义的引用 /tmp/cceVpg9m.o:在函数‘term_thread’中: pthread.c:(.text+0x15e):对‘pthread_cancel’未定义的引用 collect2: error: ld returned 1 exit status
这是由于pthread库不是Linux系统默认的库,连接时需要使用库libpthread.a,所以在使用pthread_create创建线程时,在编译中要加-pthread参数,再次编译成功。
$ gcc pthread.c -pthread
运行结果如下:
lixinxing@lixinxing-ideapad:~$ gcc pthread.c -pthread lixinxing@lixinxing-ideapad:~$ ./a.out term thread created! mid thread created! waiting term thread 0 times! waiting term thread 1 times! waiting term thread 2 times!

原创文章,转载请注明: 转载自科技爱好者博客
本文链接地址: Linux 下使用 pthread 库开发多线程学习 (https://www.tujing.site/1230)
如果博客对您有帮助,请给我 赞助
由于进程的种种缺点,所以提出了线程的概念
对!
不错。值得学习啊,顶一个