help me out with my threaded c++ mudbase - c++, pthread_cond_wait


 
Thread Tools Search this Thread
Top Forums Programming help me out with my threaded c++ mudbase - c++, pthread_cond_wait
# 1  
Old 08-24-2007
help me out with my threaded c++ mudbase - c++, pthread_cond_wait

hello,
in my free time i am writing on a c++ mud codebase, a while ago i decided that i would move to pthreads, so i could make use of smp. now i have a problem which i just cant fix - for weeks now. i have a main thread which spawns my threads, as soon as spawned they get a pthread_cond_wait, so all new threads are sleeping, until i signal them to wake and to my bidding - what is what they wont do. they just wont receive my pthread_cond_signal.
the important part of my code is this i guess:
Code:
void Thread::signal(int signal){
	int r;
	msg("Thread::signal(): '%s' received signal.\r\n", name->c_str()); 
	switch(signal)
	{
		case S_GO:
			msg("Thread::signal(): '%s' signal: S_GO\r\n", name->c_str()); 
			try { 	
				pthread_mutex_lock( &this->condition_mutex );
			}
			catch ( exception& e ) { 
				msg("EXCEPTION: Thread::signal(): '%s'.\r\n", e.what()); 
			}
			msg("Thread::signal(): '%s' is locked\r\n", name->c_str()); 
			r = pthread_cond_signal( &this->condition ); 
			msg("Thread::signal(%i): signal returns: %i\r\n", &this->condition ,r); 
			pthread_mutex_unlock( &this->condition_mutex );
			msg("Thread::signal(): '%s' is unlocked\r\n", name->c_str()); 
			break;;
		case S_PAUSE:
		break;;
		case S_DIE:
		break;;
		default:
			msg("Thread::signal(): Undefined signal '%i'.", signal);			
	};
	msg("Thread::signal(): Signal '%i' was processed.\r\n", signal); 
}

void Thread::do_loop(){
	bool loop = true,pause = true;
	int tic = itime();
	struct timespec next;        /* timeout value for the timed_wait function */
	msg("Thread::do_loop(): '%s' called me, and here i am.\r\n", name->c_str()); 
	if(name->compare("initHelper") == 0) pause = false;
	while( loop == true ){
		//if(tic == itime()) {
			msg("Thread::do_loop(): '%s' tries to lock its condition.\r\n", name->c_str()); 
			try { 	pthread_mutex_lock( &condition_mutex ); }
			catch ( exception& e ) { msg("Thread::do_loop(1): '%s'.\r\n", e.what()); }
			msg("Thread::do_loop(): '%s' locked its condition and tries to go to sleep.\r\n", name->c_str()); 
			try {
				if( pause == true ) {
					if( state == TS_NEW ){
						state = TS_READY;
						msg("NOTE: Thread '%s' is ready now.\r\n",name->c_str());
					}
					msg("Thread::do_loop(%d): '%s' id %i goes to sleep.\r\n", &this->condition,name->c_str(),this->id); 
					
					pthread_cond_wait( &(this->condition), &condition_mutex ); 
					msg("Thread::do_loop(): '%s' just awoke.\r\n", name->c_str()); 
					pause = false;
				} else {
					// Have a certain wait time ( half a second to be specific )
					next.tv_sec = itime();
					next.tv_nsec = wait;
					pthread_cond_timedwait( &condition, &condition_mutex, &next ); 
					msg("Thread::do_loop(): '%s' just awoke.\r\n", name->c_str()); 
				}
			}
			catch ( exception& e ) { 
				msg("Thread::do_loop(2): '%s'.\r\n", e.what()); 
			}
			
			//if( state == TS_READY ) state = TS_RUNNING;
			pthread_mutex_unlock( &condition_mutex );
			
			msg("Thread::do_loop(): Calling function for '%s'.\r\n", name->c_str()); 
			(*pfunction)(NULL);
			msg("Thread::do_loop(): Function for '%s' finished.\r\n", name->c_str());
			if(name->compare("initHelper") == 0) return;
			
			msg("Thread::do_loop(): Stop loop.\r\n", name->c_str());
			loop = false;
	}
	
}

you can take a look at the whole code here.

as you can see this is a more or less object oriented attempt. i think that maybe the pointer this->condition is different,when cond_wait uses it, and when cond_signal uses it. please help me out here, i am happy to provide every info and try every idea.
thanks for your attention,
sonicx
# 2  
Old 08-24-2007
Threads and signals are a bad mix.

In a threaded program you should

(a) have one thread devoted to receiving signals for the process using sigwait, this would then deal with each signal in an orderly manner. This will deal with all signals targetted at the *process*, (SIGINT, SIGQUIT etc). Do a SIG_BLOCK for all these signals in every other thread or before you create those threads so they inherit the signal mask.

(b) set up pthread_cleanup_push/pthread_cleanup_pop to protect each group of local variables to cope with SIGSEGV etc. Set up a single signal handler in the application for SIGSEGV etc that calls pthread_exit(PTHREAD_CANCELLED) or similar.

Also note that some compilers, eg g++ don't destruct C++ objects as they go out of scope during a thread cancellation.
# 3  
Old 08-24-2007
Also....

(a) do not put pthread_mutex_lock in a signal handler, this will wreak havoc.

(b) a thread cannot unblock itself, if it's it's blocked - its blocked, another thread has to send the pthead_cond_signal.

(c) avoid sending signals to threads like the plague
# 4  
Old 08-24-2007
Excellent replies, porter.

Thanks.
# 5  
Old 08-25-2007
thanks very much for your replies porter. i did not know about cleanup_push/pop yet, and after reading up a little on the functions i will surely try to integrate them into my source. i found some nice example code
here.

as for the signals - something i planned to use, quite in the manner you described, but did not know how yet. again, i did not know that sigwait function, thanks for that tip too - i shall integrate that into my main thread to catch signals send to the process there, and will try to put all normal threads into a blocking mode by setting up signal masks for them (got that right?).

what is named signals there in my code is actually more of a small event system to controll my thread wrapper class objects. other threads (the object which hold them) are supposed to use the signal function of the thread object to control (pause,go,kill) the thread pointed to by Thread->thread. i wanted to have a few threads which are there all the time, but only do work if i unpause them.
the input processing for example, the plan is to have my processing functions reside within a paused thread which i can unpause incase the socket listener receives some input on a clients socket. later i intend to add more parallelism by for example having the input processing thread spawn multiple workers which each process one clients input or a users command, with a queue and so on.

so to get back to the point, as you said
Quote:
(b) a thread cannot unblock itself, if it's it's blocked - its blocked, another thread has to send the pthead_cond_signal.
that would be the main thread in my case, which calls the signal function of the object which he also used to spawn that new thread.so the call to cond_signal would come from the main thread, but through the same object which "holds" the thread, thread id, associated mutex and condition and so on. but not from within the waiting thread itself - but within the to-be-controlled thread i do the cond_wait - thats right, isnt it?
i noticed not having something like
Code:
while(Thread->state == PAUSEME)
cond_wait(Thread->condition...)

which i will also give a try.

thanks again for your short but informative replies. hopefully ill be back to post a message of success.


---
nice pthreads tutorial for starters:
POSIX Threads Programming
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Need threaded python script

I have a single threaded bash script that I am using to create secgroup rules in openstack. The process to add the rules is taking forever. Any of you python gurus know how to convert this bash script into a thread python script? Thanks in advanced. create-secgroup-rules.sh: #!/bin/bash cat ... (2 Replies)
Discussion started by: stovie1000
2 Replies

2. Programming

multi-threaded memory leak

Hello All : I write a .c program to test the exactually resource the memory leak as follows: 1 #include <stdio.h> 2 #define NUM 100000 3 void *Thread_Run(void * arg){ 4 //TODO 5 //pthread_datch(pthread_self()); 6 int socket= (int)arg; 7 ... (1 Reply)
Discussion started by: aobai
1 Replies

3. Linux

Multi-threaded encryption @ Fedora 11

Hello, are any of the encryption programs capable of true multi-threading ? Friend of mine tells me that he's been running some testing on Fedora 11 and that the kernel doesn't support multi-threading at that level. I've been looking into TrueCrypt, encfs and both calm to support... (1 Reply)
Discussion started by: TehOne
1 Replies

4. UNIX for Advanced & Expert Users

Multi-threaded encryption @ Fedora 11

Hello, are any of the encryption programs capable of true multi-threading ? Friend of mine tells me that he's been running some testing on Fedora 11 and that the kernel doesn't support multi-threading at that level. I've been looking into TrueCrypt, encfs and both calm to support... (0 Replies)
Discussion started by: TehOne
0 Replies

5. Shell Programming and Scripting

In need of multi threaded perl assistance

I need to write a perl script to execute external programs and grab the output and return code. Each program should be killed if it has not completed within X seconds. Imagine that the script goes something like this : @commands = &get_commands(); foreach $cmd (@commands) { $pid =... (4 Replies)
Discussion started by: SandmanCL
4 Replies

6. Programming

Conditional wait using pthread_cond_wait() details

Please tell me about internal functionality of pthread_cond_wait(). How it works. Whether it actually put the thread into sleep and do the context switch or use spin locking. (1 Reply)
Discussion started by: mansoorulhaq
1 Replies

7. AIX

multi threaded program is hanging

I have a Multithreaded program which is hanging on AIX. OS Version: AIX 5.2 and thread library version : 5.2.0.75 We Initiate the process with 50 threads..when we are disconnecting from the process it hangs.There is lots of other stuff involved here.I am just sending the piece of the problem with... (0 Replies)
Discussion started by: hikrishn
0 Replies

8. Programming

threaded merge sort help

I am working on a merge sort of two files of integers, and am fuzzy on some of the logic\syntax. I need two threads, each of which will open a file, read its contents into an array, and then sort the array using qsort. One thread will operate on file f1.dat(10000 numbers) and leave its sorted... (0 Replies)
Discussion started by: AusTex
0 Replies

9. Programming

Threaded 'find' utility

I need to modify my version of find in unix and get it to create and use two POSIX threads to carry out concurrent finding operations. How do i get about doing this>? If anyone could help me it would be much appreciated. Thanx Mariuca (1 Reply)
Discussion started by: mariuca
1 Replies

10. UNIX for Dummies Questions & Answers

Threaded Discussions for Webpages

Dear All, I run a website for a non-profit. Does anyone know where I can get free or cheap software to run threaded discussions for our website? Our website is obviously running off a unix platform. Thanks (4 Replies)
Discussion started by: evertk
4 Replies
Login or Register to Ask a Question