没有参数的简单线程
这个基本示例在我们命名为 sync(main)
和 async(new thread)的两个线程上以不同的速率计数。主线程以 1Hz(1s)
计数到 15,而第二个以 0.5Hz(2s)
计数到 10。因为主线程更早完成,我们使用 pthread_join
使其等待异步完成。
#include <pthread.h>
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
/* This is the function that will run in the new thread. */
void * async_counter(void * pv_unused) {
int j = 0;
while (j < 10) {
printf("async_counter: %d\n", j);
sleep(2);
j++;
}
return NULL;
}
int main(void) {
pthread_t async_counter_t;
int i;
/* Create the new thread with the default flags and without passing
* any data to the function. */
if (0 != (errno = pthread_create(&async_counter_t, NULL, async_counter, NULL))) {
perror("pthread_create() failed");
return EXIT_FAILURE;
}
i = 0;
while (i < 15) {
printf("sync_counter: %d\n", i);
sleep(1);
i++;
}
printf("Waiting for async counter to finish ...\n");
if (0 != (errno = pthread_join(async_counter_t, NULL))) {
perror("pthread_join() failed");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
复制自此处: http : //stackoverflow.com/documentation/c/3873/posix-threads/13405/simple-thread-without-arguments ,最初由 M. Rubio-Roy 创建。