Re: Local Variable in Thread
On 13 Dez., 15:08, Manoj wrote:
void ThreadCS(void* lp)
{
EnterCriticalSection(&cs);
const string str = string((char*) lp);
.....
}
int _tmain(int argc, _TCHAR* argv[])
{
.....
.....
char szStr[99];
for(int i=0; i<numThreads; i++)
{
sprintf(szStr,"%d",i);
_beginthread(ThreadCS, 0, szStr);
}
.....
.....
}
Any clue ?
Give each thread a copy of the string instead of just a pointer. Using
a decent thread library (like Boost.Thread) it might look as simple as
this:
void my_thread_func(string const& s)
{
lock lck (cout_mutex);
cout << s << '\n';
}
int main() {
string foo = "hello";
thread t1 ( boost::bind(my_thread_func,foo) );
foo = "world";
thread t2 ( boost::bind(my_thread_func,foo) );
t1.join();
t2.join();
}
boost::bind yields a function object that stores a copy of foo in this
case. The thread's constructor stores a copy of the function object
somewhere safe, starts the thread and disposes the function object
automatically. But passing a reference to foo is also possible.
Replace foo within bind with cref(foo) where cref is a function
template from Boost.Ref (reference wrappers).
If for some reason you cannot use a decent thread library, you have to
dynamically create copies of the string, pass a pointer to the copy to
the thread and let the thread delete the copy again.