#include <stdio.h>
#include <pthread.h>
#include <sys/time.h>
#define MAX 10
pthread_t thread[MAX];
pthread_mutex_t mut;
long number=0;
int i;
void func()
{
int p=10000000;
while(p--){}
}
void *thread_func()
{
pthread_mutex_lock(&mut);
struct timeval tvStart,tvEnd;
gettimeofday(&tvStart,NULL);
func();
gettimeofday(&tvEnd,NULL);
if(((tvEnd.tv_sec-tvStart.tv_sec)*1000+(tvEnd.tv_usec-tvStart.tv_usec)/1000)>number)
{
number = (tvEnd.tv_sec-tvStart.tv_sec)*1000000+(tvEnd.tv_usec-tvStart.tv_usec);
}
printf("每次的时间: %ld微秒\n",number);
pthread_mutex_unlock(&mut);
sleep(2);
pthread_exit(NULL);
}
void thread_create(void)
{
for(i=0;i<MAX;i++)
{
if(pthread_create(&thread[i], NULL, thread_func, NULL)) //comment2
printf("线程%d创建失败!\n",i);
else
printf("线程%d被创建\n",i);
}
}
void thread_wait(void)
{
for(i=0;i<MAX;i++)
{
pthread_join(thread[i],NULL);
printf("线程%d已经结束\n",i);
}
}
int main()
{
//用默认属性初始化互斥锁
pthread_mutex_init(&mut,NULL);
printf("主函数创建线程\n");
thread_create();
printf("主函数正在等待线程完成\n");
thread_wait();
printf("time costs:%ld\n微秒",number);
return 0;
}
改成c++
void thread_wait()
void *thread_func(void *argv)
c改成这样,gcc编译也ok的
无类型的指针,它的类型将由被赋予的值来决定,如果赋予int 型变量的地址或指针,它就是int型。
第一个c多线程,参考:
本文详细介绍了使用C++实现多线程并行计算的代码实例,通过测量并比较不同线程数量下的运行时间,分析并行计算的性能提升效果。文章深入探讨了线程创建、互斥锁的应用以及获取系统时间的方法,为读者提供了一套高效并行计算解决方案。

被折叠的 条评论
为什么被折叠?



