pthread 笔记

本文通过示例展示了如何使用pthread库创建线程,并利用信号量(semaphore)进行线程间的同步操作。文中详细介绍了线程创建、等待、退出的过程及信号量的基本用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.创建线程 

    res = pthread_create(&a_thread, NULL, thread_function1, NULL);
    if (res != 0)
    {
     perror("Thread creation failure");
    }

2.等待线程结束

pthread_join

3.线程退出时,语句:

    pthread_exit(NULL);
    return NULL;

4. 互斥锁 使用前必须初始化!!!

pthread_mutex_init(&mutex, NULL);
pthread_mutex_destroy(&mutex);



4.
#include <stdio.h>
#ifdef _WIN32
#include <windows.h>
#include <stdio.h>
#define sleep Sleep
#else
#include <unistd.h>
#endif
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <semaphore.h>

sem_t bin_sem;
void *thread_function1(void *arg)
{
    printf("thread_function1--------------sem_wait\n");
    sem_wait(&bin_sem);
    printf("sem_wait OK\n");
    while (1)
    {
    }
    pthread_exit(NULL);
    return NULL;
}

void *thread_function2(void *arg)
{
    printf("thread_function2--------------sem_post\n");
    sem_post(&bin_sem);
    printf("sem_post\n");
    while (1)
    {
    }
    return NULL;
}



int main()
{
    int res;
    pthread_t a_thread;
    void *thread_result;

    res = sem_init(&bin_sem, 0, 0);
    if (res != 0)
    {
        perror("Semaphore initialization failed");
    }
     printf("sem_init\n");
        res = pthread_create(&a_thread, NULL, thread_function1, NULL);
    if (res != 0)
    {
     perror("Thread creation failure");
    }
    printf("thread_function1\n");
    sleep (5);
    printf("sleep\n");
    res = pthread_create(&a_thread, NULL, thread_function2, NULL);
    if (res != 0)
    {
         perror("Thread creation failure");
    }
    while (1)
    {
    }
}

 

 

sem:

sem_post  每执行一次  则加1

sem_wait( &st )   等待直到st大于1 才向下执行,  每次执行st减去1;

 

转载于:https://www.cnblogs.com/luoyinjie/p/7568161.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值