作业题目
Write a program to figure out π with pthread. The formula is here as follows
You should choose the appropriate N and the number the threads and evaluate how do these two factors affect the performance. Try it in the multi-CPUs or multi-cores system if possible and compare the time consumed in the single CPU with one core system. Remember to add the option of -lpthread in gcc.
Programming guide:
Beginning Linux Programming 4e (Chapter 12: POSIX Threads)
设计思路
把线程的执行任务分成若干段,每个线程执行一段,最后将每一段得到的结果相加即可得到π的近似值。
具体实现
线程的操作和函数有:
(1)线程句柄: pthread_t。下面创建了4个指向线程的句柄:
(2)创建线程:pthread_create():
同步和互斥
由于同一进程的线程之间大部分的数据都是共享的,在涉及到对共享数据进行读写操作时,就必须使用同步机制,否则就会造成线程们哄抢共享的数据,造成数据混乱甚至是丢失。在此,我们通过给线程加锁(互斥锁)来解决这一问题。
(1)互斥锁句柄:
(2)加锁和解锁:
(3)初始化互斥锁:
代码
|
|
运行结果
运行时链接-lpthread库,结果如下(设置计算的次数N=100000):
经过分析发现,子线程在主线程完成的时候都还来不及执行,故所得π值为0。解决方法是在创建线程的时候等待1秒,以保证子线程能够得到执行。修改后的代码和运行结果如下:
1234567for (int i = 0;i < numThreads; i++){//创建线程并且将thread函数传入hThread[i] = pthread_create(&hThread[i], NULL, thread, &i);//让主线程等待1秒,确保子线程能够得到执行sleep(1);}将线程数减为2,运行结果如下:
当线程数为1(单线程)时,运行结果如下:
完整代码
|
|