This sample text is one of the simplest examples of thread programming in C/C++ that I've ever seen - not that I've done that much looking. Taken from Gregory R. Andrews's book. It is also, not a terrible example of split binary semaphores.
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>

#define SHARED 1

void* producer( void* ); // The two threads
void* consumer( void* );

sem_t empty, full;
int data;
int numIters;

int main( int argc, char* argv[] )
{

pthread_t pid, cid;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM );

sem_init(&empty, SHARED, 1); // sem empty = 1
sem_init(&full, SHARED, 0 ); // sem full = 0

numIters = atoi( argv[1] );

pthread_create(&pid, &attr, producer, NULL );
pthread_create(&cid, &attr, consumer, NULL );

pthread_join(pid, NULL);
pthread_join(cid, NULL);

}

void* producer( void* argc)
{
int produced;
for( produced = 1; produced <= numIters; produced++)
{
sem_wait( &empty );
data = produced;
sem_post( &full );
}
}

void* consumer( void* argc)
{
int total = 0, consumed;
for( consumed = 1; consumed <= numIters; consumed++)
{
sem_wait( &full );
total += data;
sem_post( &empty);
}
printf( "the total is %d\n", total);
}

 

Add to My Yahoo!

Add to Google

Subscribe with Bloglines

Austin Gilbert/Male/26-30. Lives in United States/Oklahoma/Tulsa/Midtown, speaks English. Spends 40% of daytime online. Uses a Fast (128k-512k) connection. And likes computer science/photography.
This is my blogchalk: United States, Oklahoma, Tulsa, Midtown, English, Austin Gilbert, Male, 26-30, computer science, photography.

A good simple example of Pthread programming
2004/07/11