Re: C vs. C++ in pthreads...
From: Gianni Mariani (gi2nospam_at_mariani.ws)
Date: 01/23/04
- Next message: Damon: "How to do a singleton pattern with lazy instantiation?"
- Previous message: Donovan Rebbechi: "Re: Dynamic string arrays in function parameters"
- In reply to: John Ratliff: "Re: C vs. C++ in pthreads..."
- Next in thread: Donovan Rebbechi: "Re: C vs. C++ in pthreads..."
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: 23 Jan 2004 02:05:31 EST
John Ratliff wrote:
> Are you sure it works?
>
> I've tested this code on Linux and Solaris. Two different machines,
> compilers, operating systems, and processors. Seems odd they would both
> yield the same bad results while you claim it works fine.
>
> Does it print the "getting up" line in the C++ version? I never see it
> do that.
>
> I'm not saying they don't compile. They just don't run properly.
>
> The lock thing shouldn't matter. Yes, it's a problem. But I noticed this
> after I posted it, and it shouldn't affect sleep and wakeup since it
> clearly reaches the pthread_cond_wait call. If you take that out, the
> program just runs continually...
Nope - I'm wrong - it does not work. (I was looking at the strace and it
looked ok - my bad).
The problem is that the ThreadTest class is being copy constructed and
the thread that is initialized in the real constructor is pointed to the
original object.
static void *thread_run(void *arg) {
cout << "starting thread_run..." << endl;
ThreadTest obj = *(ThreadTest*)arg;
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - this is your problem
obj.report_for_work();
cout << "ending thread_run..." << endl;
return NULL;
}
Change the function to this ....
static void *thread_run(void *arg) {
cout << "starting thread_run..." << endl;
ThreadTest & obj = * static_cast<ThreadTest*>(arg);
obj.report_for_work();
cout << "ending thread_run..." << endl;
return NULL;
}
Also, add a non default copy constructor ...
ThreadTest( const ThreadTest & );
AND DON'T DEFINE IT. That way if anyone else does this - the program
won't link. You probably don't want an assignment operator either.
Also - the destructor MUST wait for the thread to exit before returning
otherwise all other kinds of hell happen.
- Next message: Damon: "How to do a singleton pattern with lazy instantiation?"
- Previous message: Donovan Rebbechi: "Re: Dynamic string arrays in function parameters"
- In reply to: John Ratliff: "Re: C vs. C++ in pthreads..."
- Next in thread: Donovan Rebbechi: "Re: C vs. C++ in pthreads..."
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|