开发者

Simple question on threads and variable copying (with no need of syncing)

If I want to pass a char* to various threads via pthread_create() and I want them to work independently what's the simplest way to do it safely?

I notice I get unstable behavior if I do

pseudo code:

func1() { // part of a loop
    Create var.. 
    func2(var); 
}

f开发者_开发技巧unc2(char* var) { // spawn a thread
    pthread_create(.....,&func3,(void*)var);
}

func3(void* var) {
    work with the var // unstable behavior
} 

There's no need for any data communication, the threads just get the var and then ignore what the rest of the program is doing. They just work on the var they got.


You don't show the details of the "Create var..." part of your program, but as Christopher Hunt correctly answered, if it isn't declared static, then it will go away when func1() returns. But worse than that, you said "no need for any data communication" and if you are creating the var once and accessing it from multiple threads you are having "data communication" whether you mean to or not (and the coordination of that parallel access to the var is up to you).

If you want each thread to really have its own copy it can mess with without disturbing other threads, you could duplicate it before each call to pthread_create(). For example, you could call strdup() to allocate a private copy of the string for the new thread and pass that copy to pthread_create().


You need to be careful of scope. If your var is declared on the stack then it will disappear once func1 one is done. Either allocate the var on the heap or as a static.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜