【发布时间】:2015-01-12 10:46:15
【问题描述】:
XUbuntu 14.04,2 个处理器。
多线程耗时0.8s,单线程耗时0.4s。
如果定义了MULTI_THREAD,那么程序将在单线程中运行。否则就是多线程程序
怎么了?
----------------code------------------------------
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MULTI_THREAD
#define NUM 10000
#define SEM_M 10
int arr[NUM];
FILE *f;
typedef struct _SemData{
sem_t sem_full;
sem_t sem_empty;
}SemData;
void InitSemData(SemData *sd){
sem_init(&sd->sem_full,0,0);
sem_init(&sd->sem_empty,0,SEM_M);
}
void DestroySemData(SemData *sd){
sem_destroy(&sd->sem_full);
sem_destroy(&sd->sem_empty);
}
void *Produce(void* data){
#ifdef MULTI_THREAD
SemData* psd=(SemData*)data;
#endif
int i;
for(i=0;i<NUM;++i){
#ifdef MULTI_THREAD
sem_wait(&psd->sem_empty);
#endif
arr[i]=i;
fprintf(f,"produce:%d\n",arr[i]);
#ifdef MULTI_THREAD
sem_post(&psd->sem_full);
#endif
}
}
void *Custom(void* data){
#ifdef MULTI_THREAD
SemData* psd=(SemData*)data;
#endif
int i,j;
for(i=0;i<NUM;++i){
#ifdef MULTI_THREAD
sem_wait(&psd->sem_full);
#endif
int tmp=0;
for(j=0;j<NUM;++j){
tmp+=arr[i];
}
arr[i]=tmp;
fprintf(f,"Custom:%d\n",arr[i]);
#ifdef MULTI_THREAD
sem_post(&psd->sem_empty);
#endif
}
}
void main(){
f=fopen("b.txt","w");
clock_t start=clock();
#ifdef MULTI_THREAD
SemData sd;
InitSemData(&sd);
pthread_t th0,th1;
pthread_create(&th0,NULL,Produce,(void*)&sd);
pthread_create(&th1,NULL,Custom,(void*)&sd);
pthread_join(th0,NULL);
pthread_join(th1,NULL);
DestroySemData(&sd);
#else
Produce(NULL);
Custom(NULL);
#endif
printf("TotalTime:%fs\n",((float)(clock()-start))/CLOCKS_PER_SEC);
fclose(f);
}
【问题讨论】:
-
如果定义了多线程,那么它会运行多线程吗?
-
锁不是免费的。锁甚至都不便宜。根据您的程序,增加的开销可能不如单线程版本。
-
看看有多少代码被执行只是为了复制一个值,然后复制+添加。换句话说,
MULTI_THREAD定义的操作很可能比它们的对应物慢约 20,这对我来说并不奇怪。
标签: c++ c linux multithreading