如何在ubuntu中使用usleep进行多线程控制

   2024-09-30 4200
核心提示:在Ubuntu中,你可以使用POSIX线程库(pthread)来创建多线程程序,并使用usleep函数来控制线程的执行首先,确保你已经安装了支持C

在Ubuntu中,你可以使用POSIX线程库(pthread)来创建多线程程序,并使用usleep函数来控制线程的执行

首先,确保你已经安装了支持C编程的开发环境。

接下来,创建一个名为thread_usleep.c的C文件,然后将以下代码复制到该文件中:

#include<stdio.h>#include <stdlib.h>#include <unistd.h>#include <pthread.h>void* thread_function(void *arg) {    int sleep_time = *((int *)arg);    printf("Thread started, sleeping for %d microseconds.\n", sleep_time);    usleep(sleep_time);    printf("Thread finished.\n");    return NULL;}int main() {    pthread_t thread1, thread2;    int sleep_time1 = 500000; // 500ms    int sleep_time2 = 1000000; // 1s    // Create the threads    if (pthread_create(&thread1, NULL, thread_function, &sleep_time1)) {        printf("Error creating thread 1.\n");        return 1;    }    if (pthread_create(&thread2, NULL, thread_function, &sleep_time2)) {        printf("Error creating thread 2.\n");        return 1;    }    // Join the threads    pthread_join(thread1, NULL);    pthread_join(thread2, NULL);    printf("All threads finished.\n");    return 0;}

这个程序创建了两个线程,每个线程都会休眠不同的时间(以微秒为单位),然后打印一条消息。

要编译和运行此程序,请打开终端,导航到包含thread_usleep.c的目录,并运行以下命令:

gcc -o thread_usleep thread_usleep.c -lpthread./thread_usleep

这将编译程序并创建一个名为thread_usleep的可执行文件。然后,运行该可执行文件以查看输出。

注意:在编译时,我们需要链接-lpthread库,因为我们使用了POSIX线程函数。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号