#include#include #define NUM_THREADS 5 void* thread_func(void* arg) { int thread_id = *(int*)arg; printf("Thread %d is running\n", thread_id); // 线程逻辑处理 for (int i = 0; i< 5; i++) { printf("Thread %d: Count %d\n", thread_id, i); } pthread_exit(NULL); } int main() { pthread_t threads[NUM_THREADS]; int thread_ids[NUM_THREADS]; for (int i = 0; i< NUM_THREADS; i++) { printf("Creating Thread %d\n", i); thread_ids[i] = i; int status = pthread_create(&threads[i], NULL, thread_func, &thread_ids[i]); if (status) { fprintf(stderr, "Error creating thread %d: %d\n", i, status); return -1; } } for (int i = 0; i< NUM_THREADS; i++) { pthread_join(threads[i], NULL); } printf("All threads have completed.\n"); return 0; }
在Linux系统中,使用C语言进行多线程编程是一种常见且重要的技巧。通过使用pthread库,可以方便地创建和管理多个线程。
在上述示例中,我们创建了5个线程,并且为每个线程指定了一个唯一的线程ID。我们通过pthread_create函数创建线程,并通过传递指向线程ID的指针作为参数。然后,在每个线程函数中,我们使用传递的线程ID执行特定的逻辑。
通过使用多线程编程,我们可以实现并行执行多个任务,从而提高程序的性能和响应能力。为了确保线程之间的同步和顺序执行,我们可以使用互斥锁和条件变量等机制。
需要注意的是,在多线程编程中,需要仔细处理线程之间的共享数据,以避免竞态条件和死锁等问题的发生。在编写多线程代码时,我们应该考虑到线程安全性,并采取适当的同步措施。
掌握Linux下的多线程编程技巧是非常重要的,它可以帮助我们充分发挥系统的性能并提升应用程序的效率。