- 1、本文档共3页,可阅读全部内容。
- 2、有哪些信誉好的足球投注网站(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
- 3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载。
- 4、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
c语言多线程编程
C 语言中的多线程编程
很久很久以前,我对C 语言的了解并不是很多,我最早听说多线程编程是用Java,其实C
语言也有多线程编程,而且更为简单、方便、强大。下面就让我们简单领略一下Unix C 语
言环境下的多线程编程吧!
下面先看一个简单的单线程程序:
/* 06.3.6
Sghello.c
Hello,world -- Single Thread
*/
#includestdio.h
#define NUM 6
int main()
{
void print_msg(char*);
print_msg(hello,);
print_msg(world!);
}
void print_msg(char* m)
{
int i;
for(i=0;iNUM;i++)
{
printf(%s,m);
fflush(stdout);
sleep(1);
}
}
下图反映了程序的执行流程:
执行结果:
$ ./sghello.exe
hello,hello,hello,hello,hello,hello,world!world!world!world!world!world!
那么如果想同时执行两个对于print_msg 函数的调用,就想使用fork 建立两个新的进程一样,
那该怎么办?这种思想清楚的体现在下图:
那么怎么才能达到这种效果呢?
我们可以使用函数pthread_create 创建一个新的线程。
函数原型:
int pthread_create(pthread_t *thread,
pthread_attr_t *attr,
void *(*func)(void*),
void *arg);
参数: thread 指向pthread_t 类型变量的指针
attr 指向pthread_attr_t类型变量的指针,或者为NULL
func 指向新线程所运行函数的指针
arg 传递给func 的参数
返回值 0 成功返回
errcode 错误
我们可以使用函数pthread_join 等待某进程结束。
函数原型:int pthread_join(pthread_t thread,void ** retval);
参数: thread 所等待的进程
retval 指向某存储线程返回值的变量
返回值: 0 成功返回
errorcode 错误
以上两个函数都包含在头文件pthread.h 中。
下面请看多线程版的Hello,world!
/* 06.3.6
Mhello1.c
Hello,world -- Multile Thread
*/
#includestdio.h
#includepthread.h
#define NUM 6
int main()
{
void print_msg(void*);
pthread_t t1,t2;
pthread_create(t1,NULL,print_msg,(void *)hello,);
pthread_create(t2,NULL,print_msg,(void *)world!\n);
pthread_join(t1,NULL);
pthread_join(t2,NULL);
}
void print_msg(void* m)
{
char *cp=(char*)m;
int i;
文档评论(0)