实验一-Linux多线程编程一Word文件下载.doc
- 文档编号:13179602
- 上传时间:2022-10-07
- 格式:DOC
- 页数:6
- 大小:71.50KB
实验一-Linux多线程编程一Word文件下载.doc
《实验一-Linux多线程编程一Word文件下载.doc》由会员分享,可在线阅读,更多相关《实验一-Linux多线程编程一Word文件下载.doc(6页珍藏版)》请在冰豆网上搜索。
i++;
i<
LEN)
{
C[i]=sin(i);
B[i]=C[i]*2;
A[i]=B[i]+C[i]
}
分别编制一段串行程序和一段多线程程序(包括四个线程),执行上述循环体,比较其执行所花费的时间。
提示:
clock()是C/C++中的计时函数,与其相关的数据类型是clock_t,通过clock()可以获得当前的系统时间。
四、实验步骤
1、打开Linux终端
2、输入命令$emacshello.c&
(文件名可以自定义)
3、编制源程序,注意加入必要的头文件#include<
pthread.h>
,对于信号量,还需要加头文件<
semaphore.h>
。
4、编译:
$gcc-ohellohello.c–lpthread对于是信号量,编译时还需要加-lrt参数。
5、执行:
./hello
五、实验要求
写出完整的源程序,给出程序执行的结果。
串行实验源代码如下:
#include<
#include<
stdio.h>
time.h>
#defineLEN1000000
voidmain()
{
time_tt1,t2;
doubleD[LEN];
inti;
doublesum=0.0;
t1=clock();
for(i=0;
LEN;
i++)
sum+=D[i];
t2=clock();
printf("
sum=%d\n"
t2-t1);
执行结果:
多线程实验源代码如下:
string.h>
pthread_tthread[4];
pthread_mutex_tmut;
intnumber=0,i;
void*thread1()
for(i=0;
i<
LEN;
i++)
{
pthread_mutex_lock(&
mut);
sum+=D[i];
pthread_mutex_unlock(&
}
pthread_exit(NULL);
void*thread2()
}
void*thread3()
void*thread4()
voidthread_create(void)
inttemp;
memset(&
thread,0,sizeof(thread));
if((temp=pthread_create(&
thread[0],NULL,thread1,NULL))!
=0)printf("
线程1创建失败!
\n"
);
else
printf("
线程1被创建\n"
thread[1],NULL,thread2,NULL))!
=0)
线程2创建失败"
线程2被创建\n"
thread[2],NULL,thread3,NULL))!
线程3创建失败"
线程3被创建\n"
if((temp=pthread_create(&
thread[3],NULL,thread4,NULL))!
线程4创建失败"
线程4被创建\n"
voidthread_wait(void)
if(thread[0]!
=0){
pthread_join(thread[0],NULL);
if(thread[1]!
=0){
pthread_join(thread[1],NULL);
if(thread[2]!
pthread_join(thread[2],NULL);
if(thread[3]!
pthread_join(thread[3],NULL);
intmain()
{clock_tt1,t2;
t1=clock();
pthread_mutex_init(&
mut,NULL);
thread_create();
thread_wait();
t2=clock();
printf("
return0;
串行实验源代码如下
math.h>
#defineLEN100000
voidmain(){
doubleA[LEN],B[LEN],C[LEN];
clock_tt1,t2;
for(i=0;
{
C[i]=sin(i);
B[i]=C[i]*2;
A[i]=B[i]+C[i];
执行结果:
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- 实验 Linux 多线程 编程