在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;
}