Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2484
  • Last Modified:

POSIX, pthreads, semaphore API

I'd like to learn more about this topic, but I'm having a hard time finding sample code, and good online-tutorials.  If anyone knows of a few sites, could you please post them?

Thanks in advance!
0
CBMLude
Asked:
CBMLude
  • 2
1 Solution
 
akshayxxCommented:
i found this tutorial really concise and helpful.. go to the IPC:semaphore section.. u can also look at other IPC methods

http://www.cs.cf.ac.uk/Dave/C/CE.html
0
 
akshayxxCommented:
0
 
CBMLudeAuthor Commented:
GREAT! I found
http://dis.cs.umass.edu/~wagner/threads_html/tutorial.html
to be very helpful.  Could I also get you or someone to explain what "Semaphore child_counter;" does?  I'm a little confused.  I think it creates child_counter of type Semaphore, but I don't know what the semaphore is initalized to...

void print_message_function( void *ptr );

Semaphore child_counter;
Semaphore worlds_turn;

main()
{
     pthread_t thread1, thread2;
     char *message1 = "Hello";
     char *message2 = "World";

     semaphore_init( &child_counter );
     semaphore_init( &worlds_turn );

     semaphore_down( &worlds_turn ); /* world goes second */
     
     semaphore_decrement( &child_counter ); /* value now 0 */
     semaphore_decrement( &child_counter ); /* value now -1 */
     /*
      * child_counter now must be up-ed 2 times for a thread blocked on it
      * to be released
      *
      */
     

     pthread_create( &thread1, pthread_attr_default,
                    (void *) &print_message_function, (void *) message1);

     semaphore_down( &worlds_turn );

     pthread_create(&thread2, pthread_attr_default,
                    (void *) &print_message_function, (void *) message2);

     semaphore_down( &child_counter );

     /* not really necessary to destroy since we are exiting anyway */
     semaphore_destroy ( &child_counter );
     semaphore_destroy ( &worlds_turn );
     exit(0);
}

void print_message_function( void *ptr )
{
     char *message;
     message = (char *) ptr;
     printf("%s ", message);
     fflush(stdout);
     semaphore_up( &worlds_turn );
     semaphore_up( &child_counter );
     pthread_exit(0);
}

0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now