This thread program shows me different answers every time

此生再无相见时 提交于 2019-12-08 05:26:26

Concerning your goal, your implementation should probably have problems. Since big_count and big is common for both threads and don't have any protection when threads are trying to modify those, your program should create errors.

Other than that, you are also not utilizing 2 threads, since both threads are doing calculation from 1 to 500000.

Since your calculation logic seems ok, you should get your desired output when you try with single thread.

If you want it to do by two threads, you can easily try this. (just to verify, not the nicest way)

  • You should have big_count1, big1 and big_count2, big2. So that variables whose names end with '1' is only using by thread1 and variables whose names end with '2' is only using by thread2.

  • Assign thread1 to check from 1 to 250000 and thread2 to from 250001 to 500000.

  • After join() s, just compare big_count1 and big_count2, then you can deduce the final answer. :))

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!