testlock.c
资源名称:NETVIDEO.rar [点击查看]
上传用户:sun1608
上传日期:2007-02-02
资源大小:6116k
文件大小:2k
源码类别:
流媒体/Mpeg4/MP4
开发平台:
Visual C++
- /* Test the thread and mutex locking functions
- Also exercises the system's signal/thread interaction
- */
- #include <signal.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include "SDL.h"
- #include "SDL_mutex.h"
- #include "SDL_thread.h"
- static SDL_mutex *mutex = NULL;
- static Uint32 mainthread;
- static SDL_Thread *threads[6];
- void printid(void)
- {
- printf("Process %u: exitingn", SDL_ThreadID());
- }
- void terminate(int sig)
- {
- printf("Process %u: raising SIGTERMn", SDL_ThreadID());
- raise(SIGTERM);
- }
- void closemutex(int sig)
- {
- Uint32 id = SDL_ThreadID();
- int i;
- printf("Process %u: Cleaning up...n", id == mainthread ? 0 : id);
- for ( i=0; i<6; ++i )
- SDL_KillThread(threads[i]);
- SDL_DestroyMutex(mutex);
- exit(sig);
- }
- int Run(void *data)
- {
- if ( SDL_ThreadID() == mainthread )
- signal(SIGTERM, closemutex);
- while ( 1 ) {
- printf("Process %u ready to workn", SDL_ThreadID());
- if ( SDL_mutexP(mutex) < 0 ) {
- fprintf(stderr, "Couldn't lock mutex: %s", SDL_GetError());
- exit(1);
- }
- printf("Process %u, working!n", SDL_ThreadID());
- SDL_Delay(1*1000);
- printf("Process %u, done!n", SDL_ThreadID());
- if ( SDL_mutexV(mutex) < 0 ) {
- fprintf(stderr, "Couldn't unlock mutex: %s", SDL_GetError());
- exit(1);
- }
- /* If this sleep isn't done, then threads may starve */
- SDL_Delay(10);
- }
- return(0);
- }
- int main(int argc, char *argv[])
- {
- int i;
- int maxproc = 6;
- /* Load the SDL library */
- if ( SDL_Init(0) < 0 ) {
- fprintf(stderr, "%sn", SDL_GetError());
- exit(1);
- }
- atexit(SDL_Quit);
- if ( (mutex=SDL_CreateMutex()) == NULL ) {
- fprintf(stderr, "Couldn't create mutex: %sn", SDL_GetError());
- exit(1);
- }
- mainthread = SDL_ThreadID();
- printf("Main thread: %un", mainthread);
- atexit(printid);
- for ( i=0; i<maxproc; ++i ) {
- if ( (threads[i]=SDL_CreateThread(Run, NULL)) == NULL )
- fprintf(stderr, "Couldn't create thread!n");
- }
- signal(SIGINT, terminate);
- Run(NULL);
- return(0); /* Never reached */
- }