没什么好介绍的!穷屌丝一个~
分类: LINUX
2007-12-16 11:32:02
要让一个thread在背景不断的执行,最简单的方式就是在该
thread执行无穷回圈,如while(1)
{},这种写法虽可行,却会让CPU飙高到100%,因为CPU一直死死的等,其实比较好的方法是,背景平时在Sleep状态,当前景呼叫背景时,背景马
上被唤醒,执行该做的事,做完马上Sleep,等待前景呼叫。当背景sem_wait()时,就是马上处于Sleep状态,当前景sem_post()
时,会马上换起背景执行,如此就可避免CPU 100%的情形了。
/*
(C) OOMusou 2006 http://oomusou.cnblogs.com
Filename : pthread_create_semaphore.cpp
Compiler : gcc 4.10 on Fedora 5 / gcc 3.4 on Cygwin 1.5.21
Description : Demo how to create thread with semaphore in Linux.
Release : 12/03/2006
Compile : g++ -lpthread pthread_create_semaphore.cpp
*/
#include <stdio.h> // printf(),
#include <stdlib.h> // exit(), EXIT_SUCCESS
#include <pthread.h> // pthread_create(), pthread_join()
#include <semaphore.h> // sem_init()
sem_t binSem;
void* helloWorld(void* arg);
int main() {
// Result for System call
int res = 0;
// Initialize semaphore
res = sem_init(&binSem, 0, 0);
if (res) {
printf("Semaphore initialization failed!!\n");
exit(EXIT_FAILURE);
}
// Create thread
pthread_t thdHelloWorld;
res = pthread_create(&thdHelloWorld, NULL, helloWorld, NULL);
if (res) {
printf("Thread creation failed!!\n");
exit(EXIT_FAILURE);
}
while(1) {
// Post semaphore
sem_post(&binSem);
}
// Wait for thread synchronization
void *threadResult;
res = pthread_join(thdHelloWorld, &threadResult);
if (res) {
printf("Thread join failed!!\n");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
void* helloWorld(void* arg) {
while(1) {
// Wait semaphore
sem_wait(&binSem);
printf("Hello World\n");
}
}