c ++ vector作为特定于线程的数据

时间:2013-11-02 11:27:30

标签: c++ multithreading

原始功能如下:

void func(int N, double R){
  vector<double> x;
  vector<double> y;
  #x.push_back(sth)y.push_back(sth) according to N
  #do some calculation using x and y. result is stored in R
}

现在我想让它在多线程中工作。向量x和y在每个线程中是独立的,意味着它们是线程私有数据。
我用Google搜索,发现我应该使用 pthread_key_create 。我读了一些例子,但仍然不知道该怎么做。在所有示例中,线程数据都是字符串或int对象。我只是用矢量替换它们但它不起作用。
---------------------------------------------我的代码是:< / p>

#include <iostream>
#include "stdio.h"
#include "errors.h"
#include <pthread.h>
#include <vector>
typedef struct Points{
    std::vector<int> X;
    std::vector<int> Y;
}Points;

pthread_key_t key;
pthread_once_t once = PTHREAD_ONCE_INIT;

void once_routine(void)
{
    int status;
    printf("Initializing key\n");
    status = pthread_key_create(&key, NULL);
    if(status != 0){
            err_abort(status, "pthread_key_create");
    }
}

void *thread_routine( void *arg)
{
    int status;
    Points *value = NULL;

    status = pthread_once(&once, once_routine);
    if(status != 0){
            err_abort(status, "pthread_once");
    }

    value = (Points *)malloc(sizeof(Points));
    if(value == NULL){
            errno_abort("malloc");
    }

    status = pthread_setspecific(key, (void *)value);
    if(status != 0){
            err_abort(status, "pthread_setspecific");
    }

    value->X.push_back(*(int *)arg);
    value->Y.push_back(*(int *)arg);

    sleep(2);
    value = (Points *)pthread_getspecific(key);
    if(value == NULL){
            printf("no thread-specific data value was associated \
                    with key\n");
            pthread_exit(NULL);
    }
    printf("%d done......\n", pthread_self());
}

int main(int argc, char **argv)
{
    pthread_t thread1, thread2;
    int status;
    int * pp1 = NULL;
    *pp1 = 111;
    status = pthread_create(&thread1, NULL, thread_routine, pp1);
    if(status != 0){
            err_abort(status, "create thread1");
    }
    int * pp2 = NULL;
    *pp2 = 222;
    status = pthread_create(&thread2, NULL, thread_routine, pp2);
    if(status != 0){
            err_abort(status, "create thread2");
    }

    pthread_exit(NULL);
}

谢谢大家。我经常使用python。这次python上的代码工作得很慢,所以我想也许我应该尝试c ++。现在我意识到这不是一个好主意,因为我很长时间没有写过c ++

0 个答案:

没有答案