免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 10510 | 回复: 5
打印 上一主题 下一主题

在一个线程中可以在创建线程或进程吗? [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2003-05-02 17:25 |只看该作者 |倒序浏览
我在一个线程中想一边执行程序一边监听server端有没有发信息过来,所以想在线程中再创建一个线程去执行监听的任务,当然接收到后也要处理.
不知道是否可行?
如果不行还有什么其他办法吗?

论坛徽章:
0
2 [报告]
发表于 2003-05-02 19:59 |只看该作者

在一个线程中可以在创建线程或进程吗?

我认为是可行的
随便做了个测试的小程序:
#include <pthread.h>;
#include <sys/types.h>;
#include <unistd.h>;
#include <iostream.h>;
#include <stdlib.h>;
#include <wait.h>;


void* anotherThreadFunc(void*j)
{
        int*k = (int*)j;
        for(int i=0;i<*k;i++)
        {
                cout<<"the cnt is:"<<i<<endl;
        }
        pthread_exit(NULL);
}

void* threadFunc(void* k)
{
        pthread_t thread;
        if(pthread_create(&thread,NULL,anotherThreadFunc,k)!=0) //error
        {
                cerr<<"create thread error"<<endl;
                exit(-1);
        }

        /* another codes to do sth. in this thread */
        /*
        ** waiting for the exit action of another thread
        */
        pthread_join(thread,NULL);
        cout<<"the second thread has finished"<<endl;
        pthread_exit(NULL);
}

int main()
{
        pthread_t thread;
        int i = 10;
        cout<<"in main process"<<endl;
        pthread_create(&thread,NULL,threadFunc,(void*)&i);
        pthread_join(thread,NULL);
        cout<<"the thread has finished"<<endl;
        return 0;
}

其运行输出为:
in main process
the cnt is:0
the cnt is:1
the cnt is:2
the cnt is:3
the cnt is:4
the cnt is:5
the cnt is:6
the cnt is:7
the cnt is:8
the cnt is:9
the second thread has finished
the thread has finished

如果要在各个线程进行通讯的话,可以在进程地址空间里划分一些空间出来存放
共享数据就可以了。
以上是个人之见,刚学不久。
caohongxin 该用户已被删除
3 [报告]
发表于 2003-05-03 21:31 |只看该作者
提示: 作者被禁止或删除 内容自动屏蔽

论坛徽章:
0
4 [报告]
发表于 2003-05-05 16:19 |只看该作者

在一个线程中可以在创建线程或进程吗?

非常感谢!

论坛徽章:
0
5 [报告]
发表于 2003-05-05 17:45 |只看该作者

在一个线程中可以在创建线程或进程吗?

用JAVA很简单!

论坛徽章:
0
6 [报告]
发表于 2003-05-06 09:20 |只看该作者

在一个线程中可以在创建线程或进程吗?

可是我用的是C呢
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP