Posix thread 多线程编程

====本文系本站原创,欢迎转载! 转载请注明出处:http://blog.csdn.net/yyplc====

用Posix thread进行多线程设计,就不怕跨平台了,因为很多OS都兼容Posix thread,如Linux/Windows等,甚至嵌入式系统上(如rt-thread)都支持posix thread API。线程有比进程体积小,速率高,速度快等优势。所以编程时,如果涉及到效率和速度时,采用pthread_create()一个线程总比fork()一个进程好些。

 

Posxi thread 线程操作主要有创建(creation),终止(termination),同步(joins,blocking),调度(scheduling),数据管理(datamanagement)和交互(interaction).


可以从以下线程框图了解线程的构架:

 

多线程间关系:


多线程间共享内存模型:

 

与普通的fork()进程不一样,线程很简单,线程并不需要维护线程列表,也不需要知道谁创建了它。以下是pthread_create()与fork()在各种平台上,性能的比较:

  • The primary motivation for using Pthreads is to realize potential program performance gains.
  • When compared to the cost of creating and managing a process, a thread can be created with much less operating system overhead. Managing threads requires fewer system resources than managing processes.

For example, the following table compares timingresults for the fork() subroutineand the pthread_create() subroutine.Timings reflect 50,000 process/thread creations, were performed with the time utility, and units are in seconds, nooptimization flags.

Note: don't expect the sytem and user times toadd up to real time, because these are SMP systems with multiple CPUs workingon the problem at the same time. At best, these are approximations run on localmachines, past and present.

Platform

fork()

pthread_create()

real

user

sys

real

user

sys

Intel 2.8 GHz Xeon 5660 (12cpus/node)

<
  • 2
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Linux多线程编程是指在Linux操作系统中使用多个线程来同时执行不同的任务,以提高程序的运行效率和响应速度。Linux提供了丰富的多线程编程接口,其中最常用的就是POSIX线程(Pthread)库。 使用Pthread库进行多线程编程的一般步骤如下: 1. 包含头文件pthread.h 2. 创建线程,使用pthread_create函数 3. 等待线程结束,使用pthread_join函数 4. 退出线程,使用pthread_exit函数 5. 销毁线程,使用pthread_cancel函数 下面是一个简单的例子,用于创建两个线程,分别输出“Hello”和“World”: ```c #include <stdio.h> #include <stdlib.h> #include <pthread.h> void *print_hello(void *arg) { printf("Hello\n"); pthread_exit(NULL); } void *print_world(void *arg) { printf("World\n"); pthread_exit(NULL); } int main(int argc, char *argv[]) { pthread_t t1, t2; // 创建线程1 if (pthread_create(&t1, NULL, print_hello, NULL) != 0) { printf("Create thread 1 error!\n"); exit(1); } // 创建线程2 if (pthread_create(&t2, NULL, print_world, NULL) != 0) { printf("Create thread 2 error!\n"); exit(1); } // 等待线程1结束 if (pthread_join(t1, NULL) != 0) { printf("Join thread 1 error!\n"); exit(1); } // 等待线程2结束 if (pthread_join(t2, NULL) != 0) { printf("Join thread 2 error!\n"); exit(1); } return 0; } ``` 在上面的例子中,我们定义了两个函数print_hello和print_world,分别用于输出“Hello”和“World”。在主函数中,我们创建了两个线程t1和t2,分别执行print_hello和print_world函数。使用pthread_join函数等待两个线程结束,最后退出程序。 除了Pthread库之外,Linux还提供了其他多线程编程接口,如OpenMP、OpenCL等。不同的接口适用于不同的场景,需要根据具体情况选择合适的接口。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值