Hi,
I would like to make an threaded app which would use pthreads. I made a linked list and I put references to running threads here.

I know that operations of adding a new thread reference to the list and removing a thread reference from the list after the thread finishes has to be mutexed.

I just want to ask if I made the mutexes in right way. So only one thread can remove or add new item to the list. Lines 10-12 and 31-36.

/**
 *	
 */
void *run_thread(void *soc) {
	t->number = (int) pthread_self();
	printf("%d\n", t->number);

	/* unimportant processing stuff here */

	pthread_mutex_lock(&lock);
	delete_thread(find_thread(&t, pthread_self()));
	pthread_mutex_unlock(&lock);

	return NULL;
}

/**
 *
 */
int main() {
	int rc, sd, ld = make_connection(44444);

	/* init mutex */
	pthread_mutex_init(&lock, NULL);

	/* now process incoming connections forever ... */
	while (1) {

		/* some stuff */

		pthread_mutex_lock(&lock);
		add_thread(&t, 0, (pthread_t) NULL);

		rc = pthread_create(&t->actual_thread, NULL, run_thread, (void *) &sd);
		assert(rc == 0);
		pthread_mutex_unlock(&lock);

		/* some stuff */

	}

	/* destroy mutex before quit */
	pthread_mutex_destroy(&lock);
	return 0;
}

It seems OK. Once you figure out the idea of threads and race conditions, it's really easy to use mutex. Just put lock before the code should be run by a thread at a time, and one unlock after it. Simple as that.

Thanks for the reaction, I just wasn't sure with this multiple locking.

This article has been dead for over six months. Start a new discussion instead.