Subject: Re: threading example
To: Pramod Srinivasan <pramodsri@yahoo.com>
From: Chris Wareham <chris.wareham@iosystems.co.uk>
List: netbsd-help
Date: 06/07/2002 13:34:34
Pramod Srinivasan wrote:
>
> I am trying interprocess locking using
> pthread_mutex_lock but have not been able to get it
> work, here is the test program and the output, what is
> wrong in the program?
>
There is no need to call fork() when using threads, as the whole idea
is to save the overhead of creating multiple 'heavyweight' processes.
Assuming you want thread 2 to block until it gets a lock on the mutex,
try the following code:
/* Tested on Linux as I don't have access to a NetBSD machine from
my current location. If the pthread emulation package you are
using is any good, then this should work for you. */
#include <stdio.h>
#include </usr/pkg/include/pthread.h>
static pthread_mutex_t global_mutex = PTHREAD_MUTEX_INITIALIZER;
static void *thread1(void *);
static void *thread2(void *);
int main(int argc, char *argv[]) {
pthread_t p1, p2;
if(pthread_create(&p1, NULL, thread1, NULL)) {
fputs("Unable to create first thread\n", stderr);
return 1;
}
if(pthread_create(&p2, NULL, thread2, NULL)) {
fputs("Unable to create second thread\n", stderr);
return 1;
}
pthread_join(p1, NULL);
return 0;
}
void *thread1(void *data) {
unsigned i;
fputs("Thread 1\n", stderr);
pthread_mutex_lock(&global_mutex);
while(1) {
fputs("Working in thread 1\n", stderr);
for(i = 0; i < 10000000; i++);
}
return NULL;
}
void *thread2(void *data) {
unsigned i;
fputs("Thread 2\n", stderr);
pthread_mutex_lock(&global_mutex);
while(1) {
fputs("**** Working in thread 2 ****\n", stderr);
for(i = 0; i < 10000000; i++);
}
return NULL;
}
Chris
--
chris.wareham@iosystems.co.uk (work)
cwareham@btinternet.com (home)