/* CopyRight GPL 2004 mmc Mike Chirico
   Created: Mon Apr 19 19:29:05 EDT 2004

   This program demonstrates the use of threads, and 
   mimics the waitpid function used by processes.

   Wait, why go through all this trouble? Why not
   just create an array of threads: pthread_t t[MAX]
   and loop it through pthread_join?

   Because ... see the man page for pthread_join

   "pthread_join  suspends  the  execution  of the calling thread until the
       thread identified by th terminates, either by  calling  pthread_exit(3)
       or by being cancelled."

   It would suspend the execution.

   Note: Don't squeeze code between the signal and the unlock
   because a thread is signaled; but, the lock may not be
   released.  I've put sleep statements in here an on Linux 2.4
   and 2.6 it eventually releases; but, takes longer than the
   sleep time.

  pthread_cond_signal (&ndone_cond);
  pthread_mutex_unlock (&ndone_mutex);

  reads and writes are always atomic for each call.  The
  N data in write(sock,buf,N) will be delivered as one

    gcc  -o thread_join_wait thread_join_wait.c -lpthread



#include <pthread.h>
#include <stdio.h>
#include <unistd.h>		/* for sleep */

#define MAX_THREADS 12
#define MIN_BASE_PRNT 10
pthread_mutex_t ndone_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t ndone_cond = PTHREAD_COND_INITIALIZER;
int ndone;

struct t_id
  int order;
  int prnt;
  char c;
  pthread_t t;
  int FLAG;

void *
f1 (void *vt_idptr)
  int i, max;
  struct t_id *t_idptr;
  char c;

  t_idptr = (struct t_id *) vt_idptr;

  max = t_idptr->prnt;
  c = t_idptr->c;

  for (i = 0; i < max; ++i)
    fputc (c, stderr);
  sleep (3);			/* can remove ... just helps to vary output */

  pthread_mutex_lock (&ndone_mutex);
  t_idptr->FLAG = 1;
  pthread_cond_signal (&ndone_cond);
  pthread_mutex_unlock (&ndone_mutex);

  return (t_idptr);

main ()

  pthread_t t;
  int i;
  int count = 0;

  struct t_id t_id[MAX_THREADS];
  struct t_id *t_idptr;		/* t_idptr is needed because each thread must update */

  /* This contains data for each thread. Each thread will get its own value in the array */
  for (i = 0; i < MAX_THREADS; ++i)
      t_id[i].FLAG = 0;
      t_id[i].prnt = MIN_BASE_PRNT + i;
      t_id[i].order = 0;
      t_id[i].c = 'a' + i;
  ndone = 0;

  for (i = 0; i < MAX_THREADS; ++i)
      if (pthread_create (&t, NULL, &f1, &t_id[i]) != 0)	/* Note address of t_id[i] is passed */
	  fprintf (stderr, "error pthread create \n");
	  return 1;
      t_id[i].t = t;

  /* It's ok if all the threads speed through. In that case, this while
     loop will only be executed once.


  while (count < MAX_THREADS)
      if (pthread_mutex_lock (&ndone_mutex) != 0)
	fprintf (stderr, "error in pthread_mutex_lock \n");
      fprintf (stderr, " ndone=%d \n", ndone);
      while (ndone == 0)
	if (pthread_cond_wait (&ndone_cond, &ndone_mutex) != 0)
	  fprintf (stderr, "error in pthread_cond_wait\n");

      for (i = 0; i < MAX_THREADS; ++i)
	  if (t_id[i].FLAG == 1)
	      if (pthread_join (t_id[i].t, (void **) &t_idptr) != 0)
		fprintf (stderr, "pthread_join");

	      fprintf (stderr, " i = %d\n", i);
	      if (&t_id[i] != t_idptr)
		  fprintf (stderr,
			   "t_id not matching t_idptr in final call: %d\n",
		  return 1;

	      t_id[i].FLAG = 2;
	      t_id[i].order = count++;
	      fprintf (stderr, " done for flag %d\n", i);
      pthread_mutex_unlock (&ndone_mutex);

  return 0;


Linux System Admin Tips: There are over 200 Linux tips and tricks in this article. That is over 100 pages covering everything from NTP, setting up 2 IP address on one NIC, sharing directories among several users, putting running jobs in the background, find out who is doing what on your system by examining open sockets and the ps command, how to watch a file, how to prevent even root from deleting a file, tape commands, setting up cron jobs, using rsync, using screen conveniently with emacs, how to kill every process for a user, security tips and a lot more. These tip grow weekly. The above link will download the text version for easy grep searching. There is also an html version here.

Breaking Firewalls with OpenSSH and PuTTY: If the system administrator deliberately filters out all traffic except port 22 (ssh), to a single server, it is very likely that you can still gain access other computers behind the firewall. This article shows how remote Linux and Windows users can gain access to firewalled samba, mail, and http servers. In essence, it shows how openSSH and Putty can be used as a VPN solution for your home or workplace.

MySQL Tips and Tricks: Find out who is doing what in MySQL and how to kill the process, create binary log files, connect, create and select with Perl and Java, remove duplicates in a table with the index command, rollback and how to apply, merging several tables into one, updating foreign keys, monitor port 3306 with the tcpdump command, creating a C API, complex selects, and much more.

Create a Live Linux CD - BusyBox and OpenSSH Included: These steps will show you how to create a functioning Linux system, with the latest 2.6 kernel compiled from source, and how to integrate the BusyBox utilities including the installation of DHCP. Plus, how to compile in the OpenSSH package on this CD based system. On system boot-up a filesystem will be created and the contents from the CD will be uncompressed and completely loaded into RAM -- the CD could be removed at this point for boot-up on a second computer. The remaining functioning system will have full ssh capabilities. You can take over any PC assuming, of course, you have configured the kernel with the appropriate drivers and the PC can boot from a CD. This tutorial steps you through the whole processes.

SQLite Tutorial : This article explores the power and simplicity of sqlite3, first by starting with common commands and triggers, then the attach statement with the union operation is introduced in a way that allows multiple tables, in separate databases, to be combined as one virtual table, without the overhead of copying or moving data. Next, the simple sign function and the amazingly powerful trick of using this function in SQL select statements to solve complex queries with a single pass through the data is demonstrated, after making a brief mathematical case for how the sign function defines the absolute value and IF conditions.

The Lemon Parser Tutorial: This article explains how to build grammars and programs using the lemon parser, which is faster than yacc. And, unlike yacc, it is thread safe.

How to Compile the 2.6 kernel for Red Hat 9 and 8.0 and get Fedora Updates: This is a step by step tutorial on how to compile the 2.6 kernel from source.

Virtual Filesystem: Building A Linux Filesystem From An Ordinary File. You can take a disk file, format it as ext2, ext3, or reiser filesystem and then mount it, just like a physical drive. Yes, it then possible to read and write files to this newly mounted device. You can also copy the complete filesystem, since it is just a file, to another computer. If security is an issue, read on. This article will show you how to encrypt the filesystem, and mount it with ACL (Access Control Lists), which give you rights beyond the traditional read (r) write (w) and execute (x) for the 3 user groups file, owner and other.

Working With Time: What? There are 61 seconds in a minute? We can go back in time? We still tell time by the sun?

Chirico img Mike Chirico, a father of triplets (all girls) lives outside of Philadelphia, PA, USA. He has worked with Linux since 1996, has a Masters in Computer Science and Mathematics from Villanova University, and has worked in computer-related jobs from Wall Street to the University of Pennsylvania. His hero is Paul Erdos, a brilliant number theorist who was known for his open collaboration with others.

Mike's notes page is souptonuts. For open source consulting needs, please send an email to All consulting work must include a donation to Logo Logo