Monday, February 28, 2022

[Linux Kernel] Semaphore Sample

#include<stdio.h>

#include<string.h>

#include<pthread.h>

#include<stdlib.h>

#include<unistd.h>

#include <semaphore.h>  /* Semaphore */


pthread_t tid[2];

int counter;

pthread_mutex_t lock;

sem_t mutex;


void* doSomeThing(void *arg)

{

    sem_wait(&mutex);       /* down semaphore */

    unsigned long i = 0;

    counter += 1;

    printf("\n Job %d started\n", counter);


    for(i=0; i<(0xFFFFFFFF);i++);

    printf("\n Job %d finished\n", counter);

    sem_post(&mutex);       /* up semaphore */

    return NULL;


}


int main(void)

{

    int i = 0;

    int err;


    sem_init(&mutex, 0, 1);      /* initialize mutex to 1 - binary semaphore */

    while(i < 2)

    {

        err = pthread_create(&(tid[i]), NULL, &doSomeThing, NULL);

        if (err != 0)

            printf("\ncan't create thread :[%s]", strerror(err));

        i++;

    }

    pthread_join(tid[0], NULL);

    pthread_join(tid[1], NULL);

    sem_destroy(&mutex);

    return 0;

}

======================================

Job 1 started

 Job 1 finished

 Job 2 started

 Job 2 finished

No comments:

Post a Comment

n8n index

 【n8n免費本地端部署】Windows版|程式安裝x指令大補帖  【一鍵安裝 n8n】圖文教學,獲得無限額度自動化工具&限時免費升級企業版功能