首页 新闻 会员 周边 捐助

程序正确,但不能成功运行创建的子线程

0
悬赏园豆:30 [待解决问题]

include <iostream>

include <pthread.h>

include <errno.h>

include <sys/types.h>

include <unistd.h>

include <string.h>

using namespace std;
/*

本意是让全局变量进行逐渐增加 但子线程总是运行不起来

*/

int num= 0;
void *mythread(void *arg)
{
int count=0;
for(int i=0;i<5000;i++)
{
//线程不能起作用
count=num;
count++;
num=count;
cout<<"num="<<num<<endl;
}
usleep(10);
return 0;
}
void *mythread1(void *arg)
{
int count=0;
for(int i=0;i<5000;i++)
{
//线程2不能起作用
count=num;
count++;
num=count;
cout<<"num="<<num<<endl;
}
usleep(10);
return 0;
}

int main()
{
//创建子线程
pthread_t thread;
pthread_t thread1;
int ret1=100;
int ret = pthread_create(&thread, NULL, mythread, NULL);
if(ret!=0)
{
cout<<"未成功创建线程1"<<endl;
return -1;
}

    ret=pthread_cancel(thread);//销毁线程 成功返回0;
    cout<<"ret="<<ret<<endl;
    if(ret!=0)
    {

            cout<<"未销毁子线程1"<<endl;
    }
    sleep(10);
    ret1 = pthread_create(&thread1, NULL, mythread1, NULL);
    if(ret1!=0)
    {                cout<<"未成功创建线程2"<<endl;
            return -1;
    }

    ret1=pthread_cancel(thread1);//销毁下城1成功返回0;
    if(ret1!=0)
    {
            cout<<"未销毁子线程2"<<endl;
    }
    sleep(10);
    cout<<"ret1=="<<ret1<<endl;
    cout<<"num=="<<num<<endl
    return 0;

}

down^to^earth的主页 down^to^earth | 初学一级 | 园豆:172
提问于:2022-03-15 19:39
< >
分享
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册