- A+
测试程序:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <semaphore.h>
#define NUM_THREADS 8
static sem_t m_sem;
pthread_mutex_t mutex;
void *PrintHello(void *args)
{
int thread_arg;
unsigned int i,j;
//static n = 0;
struct timeval start, end;
float time_use=0;
thread_arg = (int)(*((int*)args));
i = 0;j = 0;
//printf("n=%d\n",n);
//n++;
gettimeofday(&start, NULL);
while(1)
{
sem_post(&m_sem);
sem_wait(&m_sem);
if(j > 10000000) break;
pthread_mutex_lock(&mutex);
j++;
pthread_mutex_unlock(&mutex);
//printf("Hello from thread %d\n", thread_arg);
i++;
if( 0 == i%100) usleep(1);
//usleep(1);
}
gettimeofday(&end, NULL);
time_use=(end.tv_sec-start.tv_sec)*1000000+(end.tv_usec-start.tv_usec);//微秒
printf("thread %d exit, duration is %.3fms\n",thread_arg,time_use/1000.0);
return NULL;
}
int main(void)
{
int rc,t;
int *p_thread_id;
pthread_t thread[NUM_THREADS];
int res;
struct timeval start, end;
float time_use=0;
gettimeofday(&start, NULL);
res = sem_init(&m_sem, 0, 0);
if (res != 0)
{
printf("Semaphore initialization failed\n");
}
pthread_mutex_init (&mutex, NULL);
p_thread_id = (int *)malloc(sizeof(int));
for( t = 0; t < NUM_THREADS; t++)
{
*p_thread_id = t;
//printf("Creating thread %d\n", *p_thread_id);
rc = pthread_create(&thread[t], NULL, PrintHello, p_thread_id);
if (rc)
{
printf("ERROR; return code is %d\n", rc);
return EXIT_FAILURE;
}
usleep(1);//必须sleep
}
//printf("pthread_create end\n");
for( t = 0; t < NUM_THREADS; t++)
pthread_join(thread[t], NULL);
gettimeofday(&end, NULL);
time_use=(end.tv_sec-start.tv_sec)*1000000+(end.tv_usec-start.tv_usec);//微秒
printf("all threads exit, duration is %.3fms\n",time_use/1000);
printf("exit success\n");
return EXIT_SUCCESS;
}
测试结果:
不用互斥锁mutex
1.用信号量m_sem和不用信号量(也不用睡眠)比较。都会使cpu占用率达到100%,使用信号量会使速度下降很多。
2.使用usleep,会使cpu占用率下降很多,速度比用信号量明显要快。
3.既不用usleep,也不用信号量,速度最快,但会使cpu占用率达到100%。
用互斥锁mutex
4.循环100次,用一次usleep(1),占用cpu最少,运行最快。
5.除了4的情况,测试的其他情况cpu占用率都比较高,但都没到100%。
6.所有测试,运行速率差别不大,用时最低是8587.839ms,最高是11085.287ms。
7.用互斥锁,比不用互斥锁速度慢。
8.只用互斥锁和只用信号量的速度差不多。
以上结果是在我机器上的测试结果,机器型号不同,结果可能不同。
尽可能不使用互斥锁,多通道多队列的方式。