第一个c多线程

#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多线程,参考:

http://www.oschina.net/code/snippet_12_366?from=rss

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值