POSIX threads won't execute concurrently?

Peter Dufault dufault at hda.com
Mon Sep 1 09:47:41 UTC 2014


On Aug 27, 2014, at 14:11 , Martin Galvan <martin.galvan at tallertechnologies.com> wrote:

> void* thread(void* arg)
> {
>    int i;
> 
>    for (i = 0; i < INT_MAX; i++) {
>        printf("Thread %d\n", pthread_self());
>    }
> 
>    printf("End of thread %d\n", pthread_self());
> 
>    return 0;
> }
> 
> void* POSIX_Init()
> {
>    pthread_t id1, id2;
> 
>    if (pthread_create(&id1, NULL, thread, NULL) != 0) {
>        perror("Thread 1");
>    }
> 
>    if (pthread_create(&id2, NULL, thread, NULL) != 0) {
>        perror("Thread 2");
>    }
> 
>    if (pthread_join(id1, NULL) != 0) {
>        perror("Join 1");
>    }
> 
>    if (pthread_join(id2, NULL) != 0) {
>        perror("Join 2");
>    }
> 
>    puts("Done.");
> 
>    exit(0);
> }

The default scheduling behavior for RTEMS is SCHED_FIFO, which makes sense for real time behavior.  In your example you don't have any assurance that the running thread will block and go to the tail of it's priority queue.  You could put a sched_yield() after the printf() or you could try using scheduling attributes set to SCHED_RR.  If you set the scheduler to SCHED_RR your output could get jumbled and not break at the lines.

In general for well-defined thread behavior you need to handle the synchronization.

There are also other issues: whether your stdout is line-buffered or not, if it's going to a file on a file system that might need some additional flushing primitive beyond fflush() to ensure output, etc.  I suspect putting in the sched_yield() will result in "Thread 1 / Thread 2 / Thread 1... " behavior, though.


Peter
-----------------
Peter Dufault
HD Associates, Inc.      Software and System Engineering



More information about the users mailing list