新手Linux线程信号量问题,求大神指教

wenqin2 2012-10-26 09:25:33
题目要求:利用线程信号量同步输出1+2+...+10(线程1),11+12+......+20(线程二)以此类推到91+92+....+100,下面是我的代码,但是结果错了,求大神帮我看看:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <errno.h>
#include <sys/ipc.h>
#include <semaphore.h>
int sum1=0;int sum2=0;
sem_t sem1,sem2;

void *pthread1(void *arg)
{
int i;
int c;
for(c=0;c<5;c++)
{
sem_wait(&sem1);
for(i=1;i<=10;i++)
{
sum1+=i;
}
sem_post(&sem2);
printf("pthread1 num:%d\n",sum1);
}

}
void *pthread2(void *arg)
{
int j;
int a;
for(a=0;a<5;a++)
{
sem_wait(&sem2);
for(j=1;j<20;j++)
{
sum2+=j;
}


sem_post(&sem1);
printf("pthread2 num:%d\n",(sum2-sum1));
}




}

int main(int argc,char *argv[])
{
pthread_t tid1,tid2;
int ret;
ret=sem_init(&sem1,0,1);
ret=sem_init(&sem2,0,1);
if(ret!=0)
{
perror("sem_init");
exit(-1);
}
ret=pthread_create(&tid1,NULL,(void *)pthread1,NULL);
if(ret!=0)
{
perror("pthread cread1");
exit(-1);
}
ret=pthread_create(&tid2,NULL,(void *)pthread2,NULL);
if(ret!=0)
{
perror("pthread cread2");
exit(-1);
}
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
sem_destroy(&sem1);
sem_destroy(&sem2);
exit(0);
}
...全文
142 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
wenqin2 2012-10-31
  • 打赏
  • 举报
回复
哥,你看错了我的意思。我的意思是线程一输出:1+2+3+4+5+6+7+8+9+10的值,线程2输出:11+12+13+14+15+16+17+18+19+20的值。以此类推直到输出,线程二:91+92+93+94+95+96+97+98+99+100的值
mcgo 2012-10-28
  • 打赏
  • 举报
回复
1、虽然你用了信号量,但你定义了sum1, sum2,没有共享数据的概念
2、初始化信号量两个都为1,达不到同步的效果

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <errno.h>
#include <sys/ipc.h>
#include <semaphore.h>

sem_t sem1,sem2;

int cnt = 0;

void *pthread1(void *arg)
{

int i;
while(1) {
sem_wait(&sem1);
if (cnt >= 100) {
sem_post(&sem2);
pthread_exit(NULL);
}

for (i = 0; i < 10; i++) {
cnt++;
printf("pthread1 num:%d\n",cnt);
}

sem_post(&sem2);
}
}

void *pthread2(void *arg)
{

int i;
while(1) {
sem_wait(&sem2);
if (cnt >= 100) {
sem_post(&sem1);
pthread_exit(NULL);
}

for (i = 0; i < 10; i++) {
cnt++;
printf("pthread2 num:%d\n", cnt);
}

sem_post(&sem1);
}
}

int main(int argc,char *argv[])
{
pthread_t tid1,tid2;
int ret;
ret=sem_init(&sem1,0,1);
ret=sem_init(&sem2,0,0);
if(ret!=0)
{
perror("sem_init");
exit(-1);
}
ret=pthread_create(&tid1,NULL,(void *)pthread1,NULL);
if(ret!=0)
{
perror("pthread cread1");
exit(-1);
}
ret=pthread_create(&tid2,NULL,(void *)pthread2,NULL);
if(ret!=0)
{
perror("pthread cread2");
exit(-1);
}
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
sem_destroy(&sem1);
sem_destroy(&sem2);
exit(0);
}

23,115

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧