以下是一个简单的C语言并发程序样例,使用了pthread库:

#include <stdio.h>
#include <pthread.h>

#define NUM_THREADS 5

// 线程函数
void *thread_func(void *thread_id) {
    long tid = (long)thread_id;
    printf("Hello from thread %ld\n", tid);
    pthread_exit(NULL);
}

int main() {
    pthread_t threads[NUM_THREADS];
    int rc;
    long t;

    // 创建线程
    for (t = 0; t < NUM_THREADS; t++) {
        printf("Creating thread %ld\n", t);
        rc = pthread_create(&threads[t], NULL, thread_func, (void *)t);
        if (rc) {
            printf("Error: return code from pthread_create() is %d\n", rc);
            return -1;
        }
    }

    // 等待线程结束
    for (t = 0; t < NUM_THREADS; t++) {
        pthread_join(threads[t], NULL);
    }

    printf("All threads completed.\n");
    return 0;
}

该程序创建了5个线程,每个线程打印一条hello信息。主线程等待所有线程结束后输出"All threads completed."。

使用pthread库可以方便地创建和管理线程,实现并发程序

C语言并发程序样例

原文地址: https://www.cveoy.top/t/topic/eY3I 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录