如何理解并编写高效的C语言多线程源代码?

如何理解并编写高效的C语言多线程源代码?

多线程源码通常涉及使用特定编程语言的线程库,如Python的threading模块或Java的java.lang.Thread类。
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
// 线程函数
void *print_hello(void *arg) {
    int thread_id = *((int *)arg);
    printf("Hello from thread %d!
", thread_id);
    pthread_exit(NULL);
}
int main() {
    int num_threads = 5; // 线程数量
    pthread_t threads[num_threads]; // 线程ID数组
    int thread_ids[num_threads]; // 线程ID数组
    // 创建线程
    for (int i = 0; i < num_threads; i++) {
        thread_ids[i] = i;
        int rc = pthread_create(&threads[i], NULL, print_hello, (void *)&thread_ids[i]);
        if (rc) {
            printf("Error: Unable to create thread, %d
", rc);
            exit(1);
        }
    }
    // 等待所有线程结束
    for (int i = 0; i < num_threads; i++) {
        pthread_join(threads[i], NULL);
    }
    printf("All threads have finished.
");
    pthread_exit(NULL);
}

以上就是关于“c 多线程源码”的问题,朋友们可以点击主页了解更多内容,希望可以够帮助大家!

如何理解并编写高效的C语言多线程源代码?

原创文章,作者:未希,如若转载,请注明出处:https://www.kdun.com/ask/1125169.html

(0)
未希的头像未希新媒体运营
上一篇 2024-10-02 07:45
下一篇 2024-10-02 07:45

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

免费注册
电话联系

400-880-8834

产品咨询
产品咨询
分享本页
返回顶部
云产品限时秒杀。精选云产品高防服务器,20M大带宽限量抢购  >>点击进入