开发者

Multithreading - C - Duplicate Static Variable

is there anyway to duplicate some static variable each time a thread make access to them?

I post a simple example: Module testF.c

#define <stdio.h>
#include <windows.h>
#include <process.h>
#include "testF.h"

#define MAX_THREADS 10

int *var;

void  testF( void *arg ){ 
    int a,N,i;

    a = (INT_PTR)arg;
    N = (int)(10000/(int)(a+1));
    var = (int*) malloc(N*sizeof(int));
    for(i = 0; i<N; i++)
        var[i] = (int)a;
    _endthread();
}
...

And in another module main.c,

...
#include "testF.h"

int main(void){
    HANDLE   hth[MAX_THREADS];
    DWORD   dwExitCode;
    int i;
    for(i = 0; i<MAX_THREADS; i++)
         hth[i] = (HANDLE)_beginthread( testF, 0, (void*)i );

    WaitForMultipleObjects(MAX_THREADS, hth, TRUE, INFINITE);

    for(i = 0; i<MAX_THREADS; i++){
        GetExitCodeThread( hth[i], &dwExitCode );
        printf( "thread 1 exited with code %u\n", dwExitCode );
        CloseHandle( hth[i] );
    }
}

In the this example the variable i would like to duplicate is *var.

I've seen that functions like rand()开发者_如何学运维 give always the same result if called from different thread, so I think that there should be a way to do it.


Thread-local storage.


Functions like rand() generally use thread local storage to maintain intercall state on a per-thread basis. This is what you would need to do instead of using a language construct like static. Your other option is to supply the variable into the thread start function, instead of using a global or static.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜