Skip to content

Instantly share code, notes, and snippets.

@Mooophy
Last active August 29, 2015 14:27
Show Gist options
  • Select an option

  • Save Mooophy/f465512d3327598bf3e3 to your computer and use it in GitHub Desktop.

Select an option

Save Mooophy/f465512d3327598bf3e3 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define NUM_THREADS 1
// The function executed by each thread
void *PrintHello(void *threadid)
{
// Print greeting with thread ID info
long tid;
tid = (long)threadid;
printf("Hello World! It's me, thread #%ld!\n", tid);
sleep(30);
pthread_exit(NULL);
}
int main (int argc, char *argv[])
{
// Will create 5 threads, so will need a reference to each
pthread_t threads[NUM_THREADS];
int rc;
long n;
for(n = 0; n < NUM_THREADS; ++n){
printf("In main: creating thread %ld\n", n);
// Create a thread here, and get the thread to run the PrintHello
// function. Note the way the parameters are passed
rc = pthread_create(&threads[n], NULL, PrintHello, (void *)n);
// A non-zero return code means something went wrong
if (rc){
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
// Useful to call this in the main to ensure that all threads are
// kept alive. Otherwise threads that are still going will be
// automatically terminated
pthread_exit(NULL);
}
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *print_message( void *ptr );
main()
{
pthread_t thread1, thread2;
char *message1 = "Thread 1";
char *message2 = "Thread 2";
int iret1, iret2;
/* Create independent threads each of which will execute function */
iret1 = pthread_create( &thread1, NULL, print_message,
(void*) message1);
iret2 = pthread_create( &thread2, NULL, print_message,
(void*) message2);
/* Wait till threads are complete before main continues. Unless we */
/* wait we run the risk of executing an exit which will terminate */
/* the process and all threads before the threads have completed. */
pthread_join( thread1, NULL);
pthread_join( thread2, NULL);
printf("Thread 1 returns: %d\n",iret1);
printf("Thread 2 returns: %d\n",iret2);
exit(0);
}
void *print_message( void *ptr )
{
char *message;
message = (char *) ptr;
printf("%s \n", message);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment