fork download
  1. #include <bits/stdc++.h>
  2. #include <thread>
  3. #include <mutex>
  4. using namespace std;
  5. mutex vote_lock;
  6. condition_variable cv;
  7. int turn=0;
  8. class Poll{
  9. public:
  10. string PollId;
  11. string question;
  12. vector<string>options;
  13. map<string,vector<pair<string,string>>>votes;
  14. map<string,int>results;
  15. Poll(string PollId,string question,vector<string>options){
  16. this->PollId=PollId;
  17. this->question=question;
  18. this->options=options;
  19. votes.clear();
  20. results.clear();
  21. }
  22. Poll()=default;
  23. };
  24. unordered_map<string,Poll>polls;
  25. void createPoll(string question, vector<string>options){
  26. int sz = polls.size()+1;
  27. string pollId = "poll"+to_string(sz);
  28. Poll poll = Poll(pollId,question,options);
  29. polls[pollId]=poll;
  30. cout<<"Poll created successfully"<<'\n';
  31. }
  32. void updatePoll(string pollId, string question, vector<string>options){
  33. Poll *poll = &polls[pollId];
  34. (*poll).options=options;
  35. (*poll).question=question;
  36. cout<<"Poll updates successfully"<<'\n';
  37. }
  38. void deletePoll(string pollId){
  39. polls.erase(pollId);
  40. }
  41. void voteInPoll(string pollId, string userId, string option){
  42. lock_guard<mutex>lock(vote_lock);
  43. Poll *poll = &polls[pollId];
  44. (*poll).votes[option].push_back({userId,option});
  45. string optionIndex = "";
  46. optionIndex +=option[6];
  47. // cout<<"hi "<<optionIndex<<'\n';
  48. string val = (*poll).options[stoi(optionIndex)-1];
  49. cout<<val<<'\n';
  50. (*poll).results[val]++;
  51. cout<<"Vote cast successfully"<<'\n';
  52. turn++;
  53. if(turn==3){
  54. cv.notify_all();
  55. }
  56. }
  57. void viewPollResults(string pollId){
  58. unique_lock<mutex> lock(vote_lock);
  59. while(turn!=3){
  60. cv.wait(lock);
  61. }
  62. Poll *poll = &polls[pollId];
  63. cout<<"PollId: "<<(*poll).PollId<<'\n';
  64. cout<<"Question: "<<(*poll).question<<'\n';
  65. cout<<"Results: "<<'\n';
  66. for(auto it:(*poll).options){
  67. cout<<it<<": "<<(*poll).results[it]<<'\n';
  68. }
  69.  
  70.  
  71. }
  72. int main(){
  73. createPoll("What is your favorite color?", {"Red", "Blue", "Green", "Yellow"});
  74. thread t1(voteInPoll,"poll1", "user1", "Option1");
  75. thread t2(voteInPoll,"poll1", "user2", "Option2");
  76. thread t3(voteInPoll,"poll1", "user3", "Option1");
  77. viewPollResults("poll1");
  78. t1.join();
  79. t2.join();
  80. t3.join();
  81.  
  82. }
Success #stdin #stdout 0.01s 5260KB
stdin
Standard input is empty
stdout
Poll created successfully
Red
Vote cast successfully
Blue
Vote cast successfully
Red
Vote cast successfully
PollId: poll1
Question: What is your favorite color?
Results: 
Red: 2
Blue: 1
Green: 0
Yellow: 0