- 论坛徽章:
- 0
|
本帖最后由 izualzhy 于 2011-11-05 18:03 编辑
pthread编程时遇到的问题,代码在下面
当NLOOP值比较小时没有问题,mutex起作用了。
当NLOOP逐渐增大,我多次运行编译后的程序,会遇到结果不正常的情况。
不知道在各位机器上运行怎么样?
有人能给分析下么?- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <pthread.h>
- #define NLOOP 2000
- int counter; /*incremented by threads*/
- pthread_mutex_t counter_mutex = PTHREAD_MUTEX_INITIALIZER;
- void *doit(void *vptr)
- {
- int i,var;
- for ( i=0; i<NLOOP; ++i) {
- pthread_mutex_lock(&counter_mutex);
- /*printf("%x: %d\n",(unsigned int)pthread_self(),counter);*/
- counter++;
- pthread_mutex_unlock(&counter_mutex);
- /*usleep(1000);*/
- }
- return NULL;
- }
- int main(int argc, char *argv[])
- {
- pthread_t tidA,tidB;
- pthread_create(&tidA, NULL, &doit, NULL);
- pthread_create(&tidB, NULL, &doit, NULL);
- /*wait for both threads to terminate*/
- pthread_join(tidA,NULL);
- pthread_join(tidA,NULL);
- printf("counter = %d\n",counter);
- /*sleep(1);*/
- /*printf("counter = %d\n",counter);*/
- /*if (write(STDOUT_FILENO,&counter,sizeof(counter)) != sizeof(counter))*/
- /*printf("write error\n");*/
- return 0;
- }
复制代码 |
|