Date: Wed, 10 Mar 1999 21:02:56 +1000 From: Greg Black <gjb@comkey.com.au> To: Wai Chan <wai@aloha.net> Cc: freebsd-questions@FreeBSD.ORG Subject: Re: Multithreading sample Message-ID: <19990310110256.16205.qmail@alpha.comkey.com.au> In-Reply-To: <36E62FC8.73F4D37F@aloha.net> of Tue, 09 Mar 1999 22:39:36 -1000 References: <36E62FC8.73F4D37F@aloha.net>
next in thread | previous in thread | raw e-mail | index | archive | help
> I would appreciate it if someone could show me a simple multithreading
> program sample (c++ or c). Thank you in advance!
Open any book on the subject and skim the first couple of
chapters.
Here's a trivial example from one such book. I offer no comment
on its style (or on what it does, since all the books do that).
It does build and run on FreeBSD-2.2.8-R (and probably other
versions).
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <pthread.h>
void do_one_thing(int *);
void do_another_thing(int *);
void do_wrap_up(int, int);
int r1 = 0, r2 = 0;
extern int
main(void)
{
pthread_t thread1, thread2;
if (pthread_create(&thread1,
NULL, (void *) do_one_thing, (void *) &r1) != 0)
perror("pthread_create"), exit(1);
if (pthread_create(&thread2,
NULL, (void *) do_another_thing, (void *) &r2) != 0)
perror("pthread_create"), exit(1);
if (pthread_join(thread1, NULL) != 0)
perror("pthread_join"), exit(1);
if (pthread_join(thread2, NULL) != 0)
perror("pthread_join"), exit(1);
do_wrap_up(r1, r2);
return 0;
}
void do_one_thing(int *pnum_times)
{
int i, j, x;
for (i = 0; i < 4; i++) {
printf("doing one thing\n");
for (j = 0; j < 10000; j++)
x = x + i;
(*pnum_times)++;
}
}
void do_another_thing(int *pnum_times)
{
int i, j, x;
for (i = 0; i < 4; i++) {
printf("doing another \n");
for (j = 0; j < 10000; j++)
x = x + i;
(*pnum_times)++;
}
}
void do_wrap_up(int one_times, int another_times)
{
int total;
total = one_times + another_times;
printf("All done, one thing %d, another %d for a total of %d\n",
one_times, another_times, total);
}
--
Greg Black <gjb@acm.org>
To Unsubscribe: send mail to majordomo@FreeBSD.org
with "unsubscribe freebsd-questions" in the body of the message
Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?19990310110256.16205.qmail>
