Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

98版本 #2

Open
ghost opened this issue Nov 30, 2016 · 4 comments
Open

98版本 #2

ghost opened this issue Nov 30, 2016 · 4 comments

Comments

@ghost
Copy link

ghost commented Nov 30, 2016

` ThreadPool::ThreadPool(int threadNum)
{
threadsNum_ = threadNum;
createThreads();
isRunning_ = true; // <= 这里;是否应该写到前面去.
}

    int ThreadPool::createThreads()
    {
            pthread_mutex_init(&mutex_, NULL);
            pthread_cond_init(&condition_, NULL);
            threads_ = (pthread_t*)malloc(sizeof(pthread_t) * threadsNum_);
            for (int i = 0; i < threadsNum_; i++)
            {
                    pthread_create(&threads_[i], NULL, threadFunc, this); // <= 这里调用了threadFunc
            }
            return 0;
    }
    void* ThreadPool::threadFunc(void* arg)
    {
            pthread_t tid = pthread_self();
            ThreadPool* pool = static_cast<ThreadPool*>(arg);
            while (pool->isRunning_)   <= 这里;isRunning_没有初始化就拿来使用了.
            {
                    Task* task = pool->take();
                    if (!task)
                    {
                            printf("thread %lu will exit\n", tid);
                            break;
                    }

                    assert(task);
                    task->run();
            }
            return 0;
    }

`

@lizhenghn123
Copy link
Owner

是的,确实应该写到前面,逻辑上更准确,多谢。
马上修改

@lizhenghn123
Copy link
Owner

@fengluyan 已修正,多谢。see b9e604e

@ghost
Copy link
Author

ghost commented Dec 1, 2016

其实我是知乎上看到来学习的,我感觉写在后面出现问题的概率非常非常低但还是可能会出现.写在前面就肯定没问题了.感谢奉献代码供我等学习

@lizhenghn123
Copy link
Owner

是,你考虑的很周到,当时就随手一写一测,没考虑周全。

是有可能出问题的,比如创建线程很快,线程函数在isRunning_ =true之前就运行了。改后语义更明确了

不过,其实也不会有问题的,哈哈,因为这个是bool变量,在置true之前他的值是随机的,基本不会是0,所以还是会按正常情况运行的。

createThreads();   
isRunning_ = true; 

你在上面两句话的中间加一个sleep(10)等待10s,使线程函数先执行,会发现线程函数并不会退出的。
当然这是未定义行为,歪打正着。

还是修正了,多谢提醒!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant