- 论坛徽章:
- 0
|
实现了一个简单的程序, 代码后面补上,
在单核环境下, 执行 100万次操作, 只要3-4秒, 但移到多核环境下, 需要 45-50秒才能完成, cpu 十分空闲, 求教原因。
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include "mqueue.h"
static volatile int _tag = 0;
static volatile int _stop = 0;
static pthread_mutex_t _mutex;
static pthread_cond_t _true;
static pthread_cond_t _false;
static int _silence = 0;
int init_mutex()
{
pthread_cond_init(&_true, NULL);
pthread_cond_init(&_false, NULL);
pthread_mutex_init(&_mutex, NULL);
return 0;
}
void *thread_put(void *arg)
{
int i;
ssize_t rc;
int count;
count = (int) arg;
printf("#%lx put count = %d\n", pthread_self(), count);
for (i = 0; i < count; i++)
{
pthread_mutex_lock(&_mutex);
while (_tag != 0)
pthread_cond_wait(&_false, &_mutex);
_tag = 1;
if (!_silence)
printf("#%lx set true. %d\n", pthread_self(), i);
pthread_mutex_unlock(&_mutex);
pthread_cond_signal(&_true);
}
_stop = 1;
pthread_cond_signal(&_true);
printf("#%lx put finished. total(%d)\n", pthread_self(), i);
return NULL;
}
void *thread_get(void *arg)
{
int i;
ssize_t rc;
for (i = 0; !_stop; i++)
{
pthread_mutex_lock(&_mutex);
while (_tag == 0 && !_stop)
{
pthread_cond_wait(&_true, &_mutex);
}
_tag = 0;
if (!_silence)
printf("#%lx set false. %d\n", pthread_self(), i);
pthread_mutex_unlock(&_mutex);
pthread_cond_signal(&_false);
}
printf("#%lx get finished. totol(%d)\n", pthread_self(), i);
return NULL;
}
extern int optind, opterr, optopt;
int main(int argc, char **argv)
{
int tmpInt;
int i;
int c, count = 0;
char *stopString;
pthread_t *tid_puts, *tid_gets;
while (1) {
c = getopt(argc, argv, ":sSt:");
if (c == -1)
break;
switch (c) {
case 0:
break;
case 's':
case 'S':
_silence = 1;
break;
default:
break;
}
}
if (optind < argc) {
count = atoi(argv[optind]);
}
init_mutex();
if (count <= 0)
count = 1;
tid_gets = (pthread_t *)calloc(1, sizeof(pthread_t));
if (tid_gets == 0)
{
perror("calloc.");
return -1;
}
tid_puts = (pthread_t *)calloc(1, sizeof(pthread_t));
if (tid_puts == 0)
{
perror("calloc.");
return -1;
}
if (pthread_create(&tid_gets[0], NULL, &thread_get, (void *)count) != 0)
{
perror("pthread_create failed.");
return 0;
}
if (pthread_create(&tid_puts[0], NULL, &thread_put, (void *)count) != 0)
{
perror("pthread_create failed.");
return 0;
}
if (pthread_join(tid_puts[0], NULL) != 0)
printf("cant join thread %ld\n", tid_puts[i]);
if (pthread_join(tid_gets[0], NULL) != 0)
printf("cant join thread %ld\n", tid_gets[i]);
return 0;
}
|
|