---
title: "第一个c多线程"
author: "andy136566"
date: "2011-08-15T02:06:12Z"
tags: []
categories: ["编程语言"]
slug: "c"
draft: false
lastmod: "2011-08-16T19:56:16Z"
id: 1149165
url: "https://andy136566.iteye.com/blog/1149165"
---

```
#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](http://www.oschina.net/code/snippet_12_366?from=rss)