C++多线程问题

多线程问题,一直是我的一个噩梦,老是搞不清楚怎么回事,真是很惭愧呀,所以今天特地向各位的大大求教。

 

代码如下:

 

C++

 

#include "www.h"
#include<stdio.h>
#include<pthread.h>
#include<string.h>
#include<sys/types.h>
#include<unistd.h>
#include<sys/time.h>

pthread_cond_t cond;
pthread_mutex_t mutex;
long m_dwTimeout = 0;

void printids(const char *s) {
    pid_t pid;
    pthread_t tid;

    pid = getpid();
    tid = pthread_self();
    printf("%s pid %u tid %u (0x%x)\n", s, (unsigned int) pid,
            (unsigned int) tid, (unsigned
            int) tid);

    for (int i = 0; i < 100; i++) {
        printf("%s : %d\n", s, i);
    }
}

void *thr_fn1(void *arg) {
    printids("new thread1:");


    pthread_exit((void *) NULL);
}

void *thr_fn2(void *arg) {
    printids("new thread1:");


    pthread_exit((void *) NULL);
}

int main() {
    int err1, err2;
    pthread_attr_t attr1, attr2;
    pthread_t ntid1, ntid2;

    pthread_attr_init(&attr1);
    pthread_attr_init(&attr2);
    pthread_attr_setdetachstate(&attr1, PTHREAD_CREATE_DETACHED);
    pthread_attr_setdetachstate(&attr2, PTHREAD_CREATE_DETACHED);
    err1 = pthread_create(&ntid1, &attr1, thr_fn1, NULL);

    struct timeval now;
    gettimeofday(&now, NULL);
    struct timespec abstime;
    abstime.tv_nsec = now.tv_usec * 1000 + (m_dwTimeout % 1000) * 1000000;
    abstime.tv_sec = now.tv_sec + (m_dwTimeout / 1000);

    if (err1 != 0) {
        printf("can't create thread: %s\n", strerror(err1));
        return 1;
    }
//    pthread_mutex_lock(&mutex);
//    pthread_cond_timedwait(&cond, &mutex, &abstime);
//    pthread_mutex_unlock(&mutex);

    err2 = pthread_create(&ntid2, &attr2, thr_fn2, NULL);
    if (err2 != 0) {
        printf("can't create thread: %s\n", strerror(err2));
        return 1;
    }
    pthread_mutex_lock(&mutex);
    pthread_cond_timedwait(&cond, &mutex, &abstime);
//    printids("new thread2:");
    pthread_mutex_unlock(&mutex);

//    printids("main thread:");
//    sleep(1);
    return 0;
}

 

 

本人启用两个线程做i++运算,两个线程应该是竞争输出,可是结果却是按照出现顺序输出,是在是很费解,请各位大大费心了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值