在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线程函数。