在Linux中,多线程是指在一个进程中同时运行多个线程,每个线程有自己的执行流程和执行上下文,但共享进程的资源。多线程能够提高程序的并发性和性能。
在Linux下,多线程是通过pthread库来实现的。pthread库提供了一套函数接口,用于创建、控制和同步线程。
以下是一个简单的多线程实例:
#include#include // 线程函数 void* thread_func(void* arg) { int i; for (i = 0; i < 5; i++) { printf("Thread: %d\n", i); sleep(1); // 线程休眠1秒 } return NULL; } int main() { pthread_t thread; int ret; // 创建线程 ret = pthread_create(&thread, NULL, thread_func, NULL); if (ret != 0) { printf("Failed to create thread\n"); return 1; } // 主线程继续执行 int i; for (i = 0; i < 3; i++) { printf("Main: %d\n", i); sleep(1); } // 等待线程结束 pthread_join(thread, NULL); return 0; }
在上面的示例中,我们首先定义了一个线程函数thread_func
,这个函数会在新线程中执行。然后在main
函数中,我们使用pthread_create
函数创建了一个新线程,并传入了线程函数thread_func
作为参数。主线程会继续执行for
循环打印Main
,而新线程会执行for
循环打印Thread
。最后,我们使用pthread_join
函数等待新线程执行完毕。
编译并运行上述程序,将会看到主线程和新线程交替执行的输出。这是因为主线程和新线程是并行执行的。
需要注意的是,在多线程编程中,共享资源的访问需要进行同步,以避免竞态条件和数据不一致等问题。在实际使用中,可能还需要使用互斥锁、条件变量等同步机制来保证线程的正确执行。