您的位置:首页 > 其它

多线程 pthread学习之一

2016-09-19 17:05 411 查看
一个简单的多线程
例子 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);
}
每次执行结果都不同,可见是多个线程之间竞争资源的结果,多线程的执行结果的不可控性,导致我们需要使用控制条件来使用多线程,下章我们来看看怎么控制多线程的执行顺序。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: