首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

首先个c多线程

2013-11-08 
第一个c多线程#include stdio.h#include pthread.h#include sys/time.h#define MAX 10pthread_t thr

第一个c多线程

#include <stdio.h>#include <pthread.h>#include <sys/time.h>#define MAX 10pthread_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

热点排行