Linux c multi threaded programming example code

  • 2020-04-02 02:02:57
  • OfStack

Just look at the code. It has comments in it


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <time.h>
#define MAX 3
int number =0;
pthread_t id[2];
pthread_mutex_t mut; //Initializes a static mutex
void thread1(void)
{
    int i;
    printf("Hello,I am pthread1!n");
    for (i=0; i<MAX; i++)
    {
        pthread_mutex_lock(&mut);  //Lock it here to make sure the number is unique
            number ++;   
            printf("Thread1:number = %dn",number);
        pthread_mutex_unlock(&mut);
        sleep(1);  //In Linux c, sleep(minute), where the variable is in minutes
    }
    pthread_exit(NULL); //The thread terminates the execution by executing this function. The return is a null pointer type
}
void thread2(void)
{
    int j;
    printf("Hello,I'm pthread2n");
    for(j=0; j<MAX; j++)
    {
        pthread_mutex_lock(&mut);
             number ++;
             printf("Thread2:number = %dn",number);
        pthread_mutex_unlock(&mut);
        sleep(1);
    }
    pthread_exit(NULL);
}
void thread_create(void)
{
    int temp;
    memset(&id, 0, sizeof(id));
if(temp = pthread_create(&id[0], NULL, (void *)thread1, NULL)!= 0)
                          //Parameter: thread identifier pointer to thread property & NBSP; Thread running function starting address & NBSP; Run function attribute
                          //0 is returned on success
        printf("Thread 1 fail to create!n");
    else
        printf("Thread 1 createdn");
    if(temp = pthread_create(&id[1], NULL, (void *)thread2, NULL)!= 0)
        printf("Thread 2 fail to create!n");
    else
        printf("Thread 2 created!n");
 }   
void thread_wait()
{
    if(id[0] != 0)
    {
        pthread_join(id[0], NULL); //Wait for the thread to finish, then use this function to recycle the created thread resources
        printf("Thread1 completed!n");
    }
    if(id[1] != 0)
    {
        pthread_join(id[1], NULL);
        printf("Thread2 completed!n");
    }
}
int main(void)
{
int i,ret1,ret2;
pthread_mutex_init(&mut, NULL); //Dynamic mutex
    printf("Main fuction,creating thread...n");
    thread_create();
    printf("Main fuction, waiting for the pthread end!n");
    thread_wait();
    return (0);
}


Related articles: