DOC HOME SITE MAP MAN PAGES GNU INFO SEARCH PRINT BOOK
 
Threads

Basic threads management example

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <thread.h>
#define	RANGE	10
/* ARGSUSED */
void *sometask(void *dummy)
{
	thread_t thrID	= thr_self();
	unsigned seed	= getpid() * time(NULL) * (thrID + 1);
	unsigned naptime=
		(unsigned)(1 + RANGE*((double)rand_r(&seed)/(double)RAND_MAX));
	setbuf(stdout,NULL);
	(void)printf("thread %ld entering sometask\n",	thrID);
	(void)printf("thread %ld naptime %d\n",		thrID, naptime);
	(void)sleep(naptime);
	(void)printf("thread %ld leaving  sometask\n",	thrID);
	return NULL;
}

sometask

The following examples on threads management will use (either explicitly or implicitly) the function sometask that appears in ``sometask''. This function will call sleep(3C) to represent some arbitrary activity by the thread. Features to note in this example are:

#include	<stdio.h>
#include	<stdlib.h>
#include	<thread.h>
extern void	*sometask(void *);
main(int argc, char **argv)
{
     int Nthreads, i; thread_t threadID;
     if(argc != 2){
	(void)fprintf( stderr,"%s: usage: %s Nthreads\nwhere Nthreads > 0\n",
			argv[0], argv[0]);
	return 1;
     }
     if( (Nthreads = atoi(argv[1])) <= 0 ){
	(void)fprintf( stderr,"%s: usage: %s Nthreads\nwhere Nthreads > 0\n",
			argv[0], argv[0]);
	return 1;
     }
     for(i = 0; i < Nthreads; i++)
	(void)thr_create(NULL, 0, sometask, NULL, 0, NULL);
     for(i = 0; i < Nthreads; i++){
	(void)thr_join(0, &threadID, NULL);
	(void)printf("thread %ld is gone\n", threadID);
     }
     return 0;
}

Multiple threads

The program in ``Multiple threads'' creates one or more threads as follows:

#include	<stdio.h>
#include	<stdlib.h>
#include	<thread.h>
#include	<synch.h>
extern void	*sometask (void *);
static void	*repeatask(void *);
static barrier_t	common_wall;
main(int argc, char **argv)
{
     int		Nthreads, i;
     if(argc != 2){
	(void)fprintf(	stderr,"%s: usage: %s Nthreads\nwhere Nthreads > 0\n",
			argv[0], argv[0]);
	return 1;
     }
     if((Nthreads = atoi(argv[1]))>0){
	(void)barrier_init(&common_wall, Nthreads, USYNC_THREAD, NULL);
     } else {
	(void)fprintf(	stderr,"%s: usage: %s Nthreads\nwhere Nthreads > 0\n",
			argv[0], argv[0]);
	return 1;
     }
     for(i = 0; i < Nthreads; i++)
	(void)thr_create(NULL, 0, repeatask, NULL, 0, NULL);
     thr_exit(NULL);
     /*NOTREACHED*/
}
/* ARGSUSED */
static void *repeatask(void *dummy)
{
	for(;;){
		(void)printf("thread %ld at wall\n", thr_self());
		(void)barrier_wait(&common_wall);
		(void)sometask(NULL);
	}
}

barrier_wait

The example in ``barrier_wait'' is a variation of that in ``Multiple threads''. In this case:


Next topic: Dining philosophers
Previous topic: hello, world

© 2004 The SCO Group, Inc. All rights reserved.
UnixWare 7 Release 7.1.4 - 27 April 2004