Skip to content

Instantly share code, notes, and snippets.

Created May 29, 2017 13:17
Show Gist options
  • Select an option

  • Save anonymous/06781812c6078e2200cde42e8330e443 to your computer and use it in GitHub Desktop.

Select an option

Save anonymous/06781812c6078e2200cde42e8330e443 to your computer and use it in GitHub Desktop.

Revisions

  1. @invalid-email-address Anonymous created this gist May 29, 2017.
    55 changes: 55 additions & 0 deletions pthread_ex
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,55 @@
    /* Includes */
    #include <unistd.h> /* Symbolic Constants */
    #include <sys/types.h> /* Primitive System Data Types */
    #include <errno.h> /* Errors */
    #include <stdio.h> /* Input/Output */
    #include <stdlib.h> /* General Utilities */
    #include <pthread.h> /* POSIX Threads */
    #include <string.h> /* String handling */

    /* prototype for thread routine */
    void print_message_function ( void *ptr );

    /* struct to hold data to be passed to a thread
    this shows how multiple data items can be passed to a thread */
    typedef struct str_thdata
    {
    int thread_no;
    char message[100];
    } thdata;

    int global_val = 0;

    int main()
    {
    pthread_t thread1; /* thread variables */
    thdata data1; /* structs to be passed to threads */

    /* initialize data to pass to thread 1 */
    data1.thread_no = 1;
    strcpy(data1.message, "Hello!");

    pthread_create (&thread1, NULL, (void *) &print_message_function, (void *) &data1);

    while(global_val != 1)
    {
    }
    printf("end\n");
    /* exit */
    exit(0);
    } /* main() */

    /**
    * print_message_function is used as the start routine for the threads used
    * it accepts a void pointer
    **/
    void print_message_function ( void *ptr )
    {
    thdata *data;
    data = (thdata *) ptr; /* type cast to a pointer to thdata */

    /* do the work */
    printf("Thread %d says %s \n", data->thread_no, data->message);
    global_val = 1;
    while(1);
    } /* print_message_function ( void *ptr ) */