生の関数は次のようになります。
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 は各スレッドで独立しています。つまり、それらはスレッド プライベート データです。
私はグーグルで検索し、pthread_key_createを使用する必要があることを発見しました。私はいくつかの例を読みましたが、まだそれを行う方法がわかりません。すべての例で、スレッド データは文字列または int オブジェクトです。それらをベクトルに置き換えるだけですが、機能しません。
---------------------------------------------- 私のコードは:
#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 のコードの動作が遅いので、c++ を試したほうがいいのではないかと考えました。私は長い間C++を書いていなかったので、これは良い考えではないことに気付きました