Glib多线程编程

来源:互联网 发布:网络用语橙汁什么意思 编辑:程序博客网 时间:2024/05/02 01:23
// 线程初始化
void g_thread_init(GThreadFunctions *vtable);
gboolean g_thread_supported();  //检测线程是否被初始化,在程序开始处执行

// joinable设置为TRUE,则可以通过调用g_thread_join来等来线程结束
GThread* g_thread_create(GTreadFunc func, gpinter data,gboolean joinable, GError **error);
GThread* g_thread_self();
void g_thread_exit(gpointer retval);
// 等待线程return或g_thread_exit退出,其返回值是上面exit的参数,或return的返回值
gpointer g_thread_join(GThread* thread);

//加锁机制
GMutex* g_mutex_new();
void g_mutex_lock(GMutex* mutex);
// 尝试加锁,如果mutex已经被加锁,则立即返回FALSE;否则对mutex加锁,并返回TRUE
gboolean g_mutex_trylock(GMutex* mutex);
void g_mutex_unlock(GMutex* mutex);
void g_mutex_free(GMutex* mutex);

#include <glib.h>

static GMutex* mutex = NULL;

void thread_call(gpointer data)
{
gint i = GPOINTER_TO_INT(data);

g_print("%d\n", i);
g_print("Thread %d was created\n", i);
}

int main()
{
gint i;
GThread* thread = NULL;
GError*  error = NULL;
GMutex*  mutex = NULL;

if (!g_thread_supported())
{
g_thread_init(NULL);
}

mutex = g_mutex_new();

g_mutex_lock(mutex);
for (i = 1; i < 10; i++)
{
thread = g_thread_create((GThreadFunc)thread_call,(gpointer)i, FALSE, &error);
// 留有线程执行时间,便于观察
g_usleep(50);
// thread = g_thread_create((GThreadFunc)thread_call,GINT_TO_POINTER(i), FALSE, NULL);
if (thread == NULL)
{
g_critical("Create thread error: %s\n",error->message);
g_error_free(error);
}
}
g_mutex_unlock(mutex);

g_mutex_free(mutex);

return 0;
}
0 0
原创粉丝点击