You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

57 lines
2.5 KiB

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *print_message_function( void *ptr );
int 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_function, (void*) message1);
iret2 = pthread_create( &thread2, NULL, print_message_function, (void*) message2);
/*
Arguments:
thread - returns the thread id. (unsigned long int defined in bits/pthreadtypes.h)
attr - Set to NULL if default thread attributes are used.
void * (*start_routine) - pointer to the function to be threaded. Function has a single argument: pointer to void.
*arg - pointer to argument of function. To pass multiple arguments, send a pointer to a structure.
The following is a list of "thread attributes" and their default values
Attribute Default Meaning of default
contentionscope PTHREAD_SCOPE_PROCESS Thread will compete for resources within the process
detachstate PTHREAD_CREATE_JOINABLE Thread is joinable by other threads
stackaddr NULL Workspace (stack) used by thread is allocated (reserved) by the operating system
stacksize NULL Workspace size used by thread is determined by the operating system
priority 0 Priority of the thread (the lower the priority value, the higher the priority...)
policy SCHED_OTHER The scheduling policy is determined by the system
inheritsched PTHREAD_EXPLICIT_SCHED scheduling policy and parameters are not inherited but explicitly defined by the attribute object
guardsize PAGESIZE size of guard area for a thread's created stack (this area will help determine if the thread has exceeded the total amount of space that was allocated for the thread)
See https://man7.org/linux/man-pages/man3/pthread_create.3.html
*/
/* 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);
pthread_exit(NULL);
}
void *print_message_function( void *ptr )
{
char *message;
message = (char *) ptr;
printf("%s \n", message);
}