私はint countboards
というグローバル変数を持つmain.cを持っています。 main()では、pthreadを開始します。これは、1つのTCP接続を待ち受け、それを(progserver.c)を通して実行します。つまり、このスレッドは決して戻ってこないでしょう。 main()では、rm.c(RM = Ressource Manager)にあるrmmain(...)
という関数を入力します。 rm.cで私はcountboards
を読み、pthreadのprogserver.cでこの変数に書きます(どちらもextern int countboards
によってアクセス可能になっています)。異なるcファイルのpthreadのグローバル変数へのアクセス
pthreadのcountboards
に書き込んだときに、rm.cに書き込まれた後にこの変数にアクセスしたい場合は、それでもまだ古い値が残っています(この例では0 10)。どうして?
のmain.c:
int countboards;
int main(int argc, char** argv) {
countboards = 0;
pthread_t thread;
pthread_create(&thread, NULL, startProgramserver, NULL);
rmmain();
return 0;
}
rm.c:
extern int countboards;
int rmmain(vhbuser* vhbuserlist, int countvhbuser,
userio* useriolist, int countios, int usertorm, int rmtosslserver, int sslservertorm) {
while(1) {
int n;
n=read(usertorm,buf,bufc); // blocks until command comes from the user
...
board* b = findAFreeBoard(boardlist, countboards, usagelist); // here countboards should be >0, but it isn't
...
}
}
programserver.c:
extern int countboards;
void* startProgramserver(void*) {
...
sock = tcp_listen();
...
http_serve(ssl,s, sslpipes);
}
static int http_serve(SSL *ssl, int s, void* sslpipes) {
...
countboards = countboards + countboardscommands;
...
// here countboards has the new value
}
はい、「volatile」と宣言する必要がありますが、アトミック性を確保するためにmutexで保護する必要があります。 –
読み書きのためにミューテックスによって保護されている場合、volatileは必要ありません(パフォーマンスのみが害です) – bdonlan
はこのようにして渡しますか? 'pthread_create(&thread、NULL、startProgramserver、&countboards);そして、void * backからintに行くスレッドでは? 2つの変数があるときはどうなりますか? 'int'と' board'変数を渡すにはどうすればいいですか( 'board'は自作構造体です)? – Berschi