ch4-create2
Chapter_4 create1 | primes |
create2.c ALP, p. 65-66
#include <stdio.h> // fputc(), stderr(), NULL
#include <pthread.h> // for pthread_t, pthread_create(), pthread_join()
#include <unistd.h> // for sleep()
struct char_print_parms // Parameters to print function
{
char character; // The character to print
int count; // The number of times to print it
};
/* Prints a number of characters to stderr, as given by `parameters',
which is a pointer to a struct char_print_parms */
void * char_print (void * parameters)
{ /* Cast the cookie pointer to the right type: */
struct char_print_parms * p = (struct char_print_parms*) parameters;
int i;
for (i = 0; i < p->count; i++)
{
fputc (p->character, stderr);
sleep(1); // pause for 1 second
}
return NULL;
}
int main()
{
pthread_t thread1_id, thread2_id;
struct char_print_parms thread1_args, thread2_args;
thread1_args.character = 'x'; // Create a thread to print
thread1_args.count = 30; // 30 'x's
pthread_create (&thread1_id, NULL, &char_print, &thread1_args);
thread2_args.character = 'o'; // Create a thread to print
thread2_args.count = 20; // 20 'o's
pthread_create (&thread2_id, NULL, &char_print, &thread2_args);
/* Make sure the first thread has finished: */
pthread_join (thread1_id, NULL);
/* Make sure the second thread has finished: */
pthread_join (thread2_id, NULL);
fputc ('\n', stderr);
return 0; // Now we can safely return
}
/*
gcc create2.c -o create2 -lpthread
./create2
xoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxooxxxxxxxxxxx
./create2
xoxoxoxoxoxooxoxoxoxoxoxoxoxoxoxoxoxoxoxxxxxxxxxxx
*/
Chapter_4 create1 | BACK_TO_TOP | primes |
Comments
Post a Comment