多线程 pthread学习之一
2016-09-19 17:05
411 查看
一个简单的多线程
例子 thread_demo1.c :
命令行编译: gcc -g thread_demo.c -lpthread
一个c++的线程的例子:
例子 thread_demo1.c :
<pre name="code" class="cpp">#include <stdio.h> #include <stdlib.h> #include <time.h> #include <pthread.h> static void wait(void) { time_t start_time = time(NULL); while (time(NULL) == start_time) { /* do nothing except chew CPU slices for up to one second */ } } static void *thread_func(void *vptr_args) { int i; for (i = 0; i < 20; i++) { fputs(" b\n", stderr); wait(); } return NULL; } int main(void) { int i; pthread_t thread; if (pthread_create(&thread, NULL, thread_func, NULL) != 0) { return EXIT_FAILURE; } for (i = 0; i < 20; i++) { puts("a"); wait(); } if (pthread_join(thread, NULL) != 0) { return EXIT_FAILURE; } return EXIT_SUCCESS; }
命令行编译: gcc -g thread_demo.c -lpthread
一个c++的线程的例子:
#include <iostream> #include <pthread.h> using namespace std; #define NUM_THREADS 6 //线程数量 //函数返回的是函数指针,便于后面作为参数 void * thread_func(void* args) { cout << "hello thread ..." << endl; } int main() { //线程id pthread_t tids[NUM_THREADS]; for( int i = 0; i < NUM_THREADS; i++) { int id = pthread_create(&tids[i], NULL, thread_func, NULL); if (id != 0) { cout << "current thread error:" << id << endl; } else { cout << "current thread id:" << tids[i] << endl; } } pthread_exit(NULL); }每次执行结果都不同,可见是多个线程之间竞争资源的结果,多线程的执行结果的不可控性,导致我们需要使用控制条件来使用多线程,下章我们来看看怎么控制多线程的执行顺序。
相关文章推荐
- Linux多线程Pthread学习小结
- Linux多线程Pthread学习小结
- pthread多线程编程的学习小结
- pthread多线程编程的学习小结
- 树莓派学习系列 ——多线程pthread_create(,,,)
- Linux之多线程及互斥锁pthread_mutex_t的学习
- Linux多线程Pthread学习小结
- Posix pthread 多线程再学习
- Linux多线程学习(九)pthread_kill
- clone的fork与pthread_create创建线程有何不同&pthread多线程编程的学习小结
- iOS-多线程编程学习之pthread创建线程(二)
- Linux多线程Pthread学习小结
- Linux多线程学习(六)pthread_once
- pthread多线程编程的学习小结
- clone的fork与pthread_create创建线程有何不同&pthread多线程编程的学习小结
- pthread多线程基础知识学习
- Linux多线程学习(五)pthread_equal
- pthread多线程编程的学习小结
- Linux多线程Pthread学习小结
- Linux多线程Pthread学习小结