创建一个用glib编写的程序,有两个子线程,各自每一秒打印输出自学的线程名字。
时间: 2024-03-18 09:41:28 浏览: 21
以下是一个使用Glib编写的程序,有两个子线程,每个线程每一秒打印输出自己的线程名字:
```c
#include <glib.h>
#include <stdio.h>
void *thread1(void *data)
{
while (1) {
printf("Thread 1\n");
g_usleep(1000000); // 1秒
}
return NULL;
}
void *thread2(void *data)
{
while (1) {
printf("Thread 2\n");
g_usleep(1000000); // 1秒
}
return NULL;
}
int main(int argc, char *argv[])
{
GThread *t1, *t2;
// 初始化Glib
g_thread_init(NULL);
// 创建线程1
t1 = g_thread_create((GThreadFunc)thread1, NULL, TRUE, NULL);
// 创建线程2
t2 = g_thread_create((GThreadFunc)thread2, NULL, TRUE, NULL);
// 等待线程1和线程2结束
g_thread_join(t1);
g_thread_join(t2);
return 0;
}
```
在这个程序中,我们使用了GThread库来创建线程,并使用g_usleep()函数在每个线程中添加了一秒的延迟。在主函数中,我们首先初始化了Glib,然后创建了两个线程。最后,我们使用g_thread_join()函数等待线程1和线程2结束。