2008年10月26日星期日

linux编程学习之thread

linux下的sleep函数原型为: unsigned int sleep(unsigned int seconds);
MFC中的是微秒,linux下的是秒。

linux下用微秒的线程休眠函数是: void usleep(unsigned long usec);
int usleep(unsigned long usec); /* SUSv2 */
或者用select函数+timeval结构也可以(最多精确到微秒),
或者用pselect函数+timespec(可以精确到纳秒,足够精确了!)

需要注意的是:Linux的最小时间单位为10ms,当usleep设置的值小于10时,usleep其实sleep的时间还是10ms 。

附:linux生成一个线程,主线程与新生线程通过semphore通讯,延迟0.5s。
/*
Filename : thread_bg.c
Description : Demo how to create thread with semaphore in Linux.
Release : 27/10/2008
Compile : g++ -lpthread thread_bg
*/
#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;
int NUM;

void* helloWorld(void* arg);

int main() {
// Result for System call
int res = 0;

NUM = 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);
//sleep(1);//sleep 1 second
usleep(500000); //usec
}

// 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! %d\n",++NUM);
}
}