APUE 多线程排序

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/time.h>
#include <limits.h>

#define NTHR (8)
#define NUMNUM 8000000L
#define TNUM (NUMNUM/NTHR)

pthread_barrier_t b;

long nums[NUMNUM];
long snums[NUMNUM];

int complong(const void *arg1, const void *arg2)
{
    long l1 = *(long*)arg1;
    long l2 = *(long*)arg2;

    if (l1 == l2) return 0;
    if (l1 < l2) return -1;
    return 1;

}

void* thr_fn(void *arg)
{
    long idx = (long)arg;
    qsort(&nums[idx], TNUM, sizeof(long), complong);
    pthread_barrier_wait(&b);
    return ((void *)0);
}

void merge()
{
    long idx[NTHR];
    long i, minidx, sidx, num;

    for (i = 0; i < NTHR; i++) 
        idx[i] = i *TNUM;

    for (sidx = 0; sidx < NUMNUM; sidx++) {
        num = LONG_MAX;
        for (i = 0; i < NTHR; i++) {
            if ((idx[i] < (i+1) * TNUM) && (nums[idx[i]] < num)) {
                num = nums[idx[i]];
                minidx = i;
            }
        }

        snums[sidx] = nums[idx[minidx]];
        idx[minidx]++;
    }
}

int main(int argc, char *argv[])
{
    unsigned long i;
    struct timeval start, end;
    long long startuser, endusec;
    double elapsed;
    int err;
    pthread_t tid;

    srandom(1);
    for (i = 0; i < NUMNUM; i++) {
        nums[i] = random();
    }

    gettimeofday(&start, NULL);
    pthread_barrier_init(&b, NULL, NTHR + 1);

    for (i = 0; i < NTHR; i++) {
        err = pthread_create(&tid, NULL, thr_fn, (void *)(i * TNUM));
        if (err != 0) {
            perror("can't create thread!");
        }
    }
    pthread_barrier_wait(&b);
    merge();
    gettimeofday(&end, NULL);

    startuser = start.tv_sec * 1000000 + start.tv_usec;
    endusec = end.tv_sec * 1000000 + end.tv_usec;
    elapsed = (double)(endusec - startuser) / 1000000.0;

    printf("sort took %.4f seconds\n", elapsed);
#if 0
    for (i = 0; i < NUMNUM; i++) {
        printf("%d ", nums[i]);
    }
#endif

    exit(0);

}

 

转载于:https://my.oschina.net/tsh/blog/1498616

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值