多线程 pthread学习之一

本文提供了两个多线程编程示例,一个用C语言实现,另一个为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);
}

每次执行结果都不同,可见是多个线程之间竞争资源的结果,多线程的执行结果的不可控性,导致我们需要使用控制条件来使用多线程,下章我们来看看怎么控制多线程的执行顺序。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值