c_cpp 多线程应用程序,用于添加整数数组。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 多线程应用程序,用于添加整数数组。相关的知识,希望对你有一定的参考价值。

// Question Nine
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>

pthread_mutex_t lock;

typedef struct {
    int start;
    int stop;
    int *array;
    int *result;
} Job;

void *add (void *thing) {
    int result = 0;
    Job *job = (Job*) thing;

    for (int i = job->start; i < (job->stop + 1); ++i) {
        result += job->array[i];
    }

    pthread_mutex_lock(&lock);
    *job->result += result;
    pthread_mutex_unlock(&lock);
    return 0;
}

int sarray(int n, int t, int *values) {
    pthread_t tid[t];
    pthread_mutex_init(&lock, NULL);

    // Split into even nunber of threads by t
    int thread_share = n/t;
    int remaining = n;
    int index = 0;
    int result = 0;

    Job work[t];
    for (int i = 0; i < t; ++i) {
        Job current = work[i];
        current.start = index;
        if (remaining < thread_share) {
            current.stop = remaining;
        } else {
            current.stop = index + thread_share - 1;
        }

        current.array = values;
        current.result = &result;

        work[i] = current;
        remaining -= thread_share;
        index = current.stop + 1;
        pthread_create(&tid[i], NULL, add, &work[i]);
    }

    for (int i = 0; i < t; i++) {
        pthread_join(tid[i], NULL);
    }

    // pthread_mutex_destroy(&lock);
    return result;
}

int main (int argc, char **argv) {
    int array[10] = {1,2,3,4,5,6,7,8,9,10};
    int result = sarray(10, 10, array);

    printf("Result: %d\n", result);
    return result;
}

以上是关于c_cpp 多线程应用程序,用于添加整数数组。的主要内容,如果未能解决你的问题,请参考以下文章

使用多线程时如何添加到列表?

c_cpp 用于检查输入是整数还是字符串的程序

c_cpp 用于检查给定整数是正还是负的C程序

java多线程同时向一个数组arraylist添加元素,遍历这个集合

c_cpp 找到一个整数数组中包含最大乘积的对

c_cpp 找到整数数组中的第一个重复元素