多线程问题,一直是我的一个噩梦,老是搞不清楚怎么回事,真是很惭愧呀,所以今天特地向各位的大大求教。
代码如下:
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++运算,两个线程应该是竞争输出,可是结果却是按照出现顺序输出,是在是很费解,请各位大大费心了。