分类: LINUX
2006-05-26 10:21:38
|
提示: SDL_CreateThread()的第二个参数将被传递给新线程。你可以传入一个放在栈上的值,也可以传入一个供线程使用的数据指针。 |
例程:#include "SDL_thread.h"
int global_data = 0;
int thread_func(void *unused)
{
int last_value = 0;
while ( global_data != -1 ) {
if ( global_data != last_value ) {
printf("数据改变为 %d\n", global_data);
last_value = global_data;
}
SDL_Delay(100);
}
printf("线程退出\n");
return(0);
}
{
SDL_Thread *thread;
int i;
thread = SDL_CreateThread(thread_func, NULL);
if ( thread == NULL ) {
fprintf(stderr, "无法创建线程: %s\n", SDL_GetError());
return;
}
for ( i=0; i<5; ++i ) {
printf("更改数据为 %d\n", i);
global_data = i;
SDL_Delay(1000);
}
printf("通知线程退出\n");
global_data = -1;
SDL_WaitThread(thread, NULL);
}
|
|
提示: 任何可能会被多个线程访问的数据都应该用mutex保护起来。 |
例程:#include "SDL_thread.h"
#include "SDL_mutex.h"
int potty = 0;
int gotta_go;
int thread_func(void *data)
{
SDL_mutex *lock = (SDL_mutex *)data;
int times_went;
times_went = 0;
while ( gotta_go ) {
SDL_mutexP(lock); /* 锁住potty */
++potty;
printf("线程%d 正在使用potty\n", SDL_ThreadID());
if ( potty > 1 ) {
printf("哦,有人在用potty!\n");
}
--potty;
SDL_mutexV(lock);
++times_went;
}
printf("好了\n");
return(times_went);
}
{
const int progeny = 5;
SDL_Thread *kids[progeny];
SDL_mutex *lock;
int i, lots;
/* 创建同步锁 */
lock = SDL_CreateMutex();
gotta_go = 1;
for ( i=0; i |