I have recently started learning the wonders of pthreads according to POSIX 1003.1c.
PThreads may seem complex, but they are basically simple threads that we use in the class to create parallel behavior: https://computing.llnl.gov/tutorials/pthreads/
As I am still learning, my teacher gave us a C code to toy with:
/* Creates two threads, one printing 10000 "a"s, the other printing
10000 "b"s.
Illustrates: thread creation, thread joining. */
#include <stddef.h>
#include <stdio.h>
#include <unistd.h>
#include "pthread.h"
void * process(void * arg)
{
int i;
fprintf(stderr, "Starting process %s\n", (char *) arg);
for (i = 0; i < 100; i++) {
write(1, (char *) arg, 1);
// fprintf(stdout, (char *) arg, 1);
}
return NULL;
}
int main()
{
int retcode;
pthread_t th_a, th_b;
void * retval;
retcode = pthread_create(&th_a, NULL, process, "a");
if (retcode != 0) fprintf(stderr, "create a failed %d\n", retcode);
retcode = pthread_create(&th_b, NULL, process, "b");
if (retcode != 0) fprintf(stderr, "create b failed %d\n", retcode);
retcode = pthread_join(th_a, &retval);
if (retcode != 0) fprintf(stderr, "join a failed %d\n", retcode);
retcode = pthread_join(th_b, &retval);
if (retcode != 0) fprintf(stderr, "join b failed %d\n", retcode);
return 0;
}
-
Instructions to run and compile (for linux):
- Run command: `sudo apt-get install build-essential`
- Donwload this code (obviously xD)
- Use the following command to compile: `gcc -D_REENTRANT filenName.c -lpthread`
- Run the result by using the command: `./a.out`
Everything works but I don't understand why my output order is different depending on the use of write
or fprintf
.
When I use write
I get a random output of letters like the following:
Starting process a
aaaaaaaaaaaaaaaaaaaaaaaaaaaaStarting process b
aaababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
But when I use fprintf
I always get the get an output similar to:
Starting process a
Starting process b
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaababbabaabaabaababbabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
In this case, the text "Starting process" always appears first and is not mixed with the rest of the output. Why is this happening? Is it because write
is very fast and fprintf
is slower?
As a C programmer, which one should I use and why?
fprintf()
line seems to be entirely wrong. – Pavel Šimerda Sep 17 '14 at 8:29