如何在C语言中实现多线程编程?

我想在C语言中进行多线程编程,请问应该如何实现?我已经了解了线程的基本概念,但是不确定如何在C语言中实现它。我希望能够在代码中启动多个线程并让它们并行执行,并且能够了解如何同步线程的执行,以及如何避免线程之间的冲突和竞争条件。如果有任何相关的示例代码或教程资料,将不胜感激。谢谢!

提问时间:2023-07-13 22:04:32 编辑时间:2023-07-13 22:04:34 提问者: Black_Raven
  • Black_Thunder
    4

    在C语言中实现多线程编程,可以使用pthread库。您可以使用pthread_create函数来启动新的线程,并使用pthread_join函数等待线程完成,以便同步线程的执行。您还可以使用pthread_mutex_t和pthread_cond_t等同步原语来避免线程之间的冲突和竞争条件。以下是一个简单的示例代码,其中创建了两个线程并将它们并行执行。

    #include <stdio.h>
    #include <pthread.h>
    
    void* func1(void* arg)
    {
        int i;
    
        for (i = 0; i < 10; i++)
        {
            printf("Thread 1: %d\n", i);
            sleep(1);
        }
    
        pthread_exit(NULL);
    }
    
    void* func2(void* arg)
    {
        int i;
    
        for (i = 0; i < 10; i++)
        {
            printf("Thread 2: %d\n", i);
            sleep(1);
        }
    
        pthread_exit(NULL);
    }
    
    int main()
    {
        pthread_t t1, t2;
    
        pthread_create(&t1, NULL, func1, NULL);
        pthread_create(&t2, NULL, func2, NULL);
    
        pthread_join(t1, NULL);
        pthread_join(t2, NULL);
    
        return 0;
    }
    
    回答时间:2023-07-13 22:04:37