C++ - Play multiple Beeps simultaneously via multi-threading? - c++

Is it possible to play 2 or more beeps (from windows.h) simultaneously? I am very inexperienced when it comes to multi-threading but shouldn't the following do the job?
#include <thread>
#include <windows.h>
#include <iostream>
using namespace std;
void operation1();
void operation2();
int main()
{
thread task1 = thread(operation1);
thread task2 = thread(operation2);
task2.join();
task1.join();
return 0;
}
void operation1()
{
Beep(523, 1000);
}
void operation2()
{
Beep(262, 1000);
}
When I compile and run this the program only plays a beep with a frequency of 262 Hz. Does that mean, that only operation 2 is called or are the two sounds somehow still blocking each other?

The Beep method is actually came from dinosaur era, when PCs had internal speakers.
Guess what? The internal speaker could play only one sound of one frequency at a time.
Nowadays, Windows just simulate that behavior, so that nothing in the system can make Windows play 2 or more BEEPS at a time.

Your code exposes a problem I see very often (usually better hidden, though), which produces unexpected results and leaves the developers hairless. Namely, you fail to take into account lifetime of your threads.
When you start a new thread (no matter how, say, using C++11 std::thread) the starter thread continues executing (in your case, main()). Unless you ask for it, starter thread does not wait for anything to happen to the thread it just started. It just moves on, and than main() returns, and by definition, it means your program stops executing. Nobody gurantees you that the threads you've started had any chance to perform any operation at all!
You need to make a habit of waiting for threads to finish before returning from main - for example, by using thread::join. Actually, c++11 thread class will abort the program in it's destructor unless the thread was either joined, or detached - but I consider detached threads to be a of a bad design choice.

Related

How to implement Priority Preemptive Scheduling (similar to interrupts) with threads in C++

I want to write a C++ program on Windows (but preferably to support cross-platform) in which I have two threads that are scheduled based on Priority Preemptive Scheduling - which is like an interrupt behavior (when the interrupt occurs, the main thread pauses wherever it is and only when the interrupt thread goes back to sleep the main thread will resume from where it was paused).
These are the threads:
Thread T_main
Thread T_interrupt.
T_main runs all the time in a while loop.
T_interrupt is supposed to be executed once every second and it does something very quick.
The code in T_main is rather large (thousands of lines of code).
It must be extremely time accurate.
I want that when the time comes for the T_interrupt thread to run, it will be prioritized so that it will run without interruption until it finishes and only then the thread T_main will resume from where it paused.
If you are wondering what I am trying to do then here is a basic explanation:
Basically, I am running a simulation of my embedded project. I mocked my entire hardware and I want to run my application on a simulator on the PC. The purpose is to test the logic implementation of my application. Compiler differences and other imperfections are taken into consideration. What is critical for me is to be able to simulate a 1-second tick timer based interrupt that exists on my MCU. I am finding it difficult to simulate this behavior as thread scheduling seems to be cooperative and not preemptive.
I tried using priorities and setting scheduling methods such as Round Robin SCHED_RR or FIFO SCHED_FIFO but in all cases the scheduling implementation is still cooperative and not preemptive.
Here is my code:
#include <iostream>
#include <thread>
#include <pthread.h>
#include <string>
using namespace std;
void MainApplicationFunc(void)
{
// Infinite loop in which the app is running
while(1)
{
MainProgram();
}
}
void TickTimerInterruptFunc()
{
while(1)
{
TickTimer();
std::this_thread::sleep_for(1s);
}
}
void setScheduling(std::thread &th, int policy, int priority)
{
sched_param sch_params;
sch_params.sched_priority = priority;
if(pthread_setschedparam(th.native_handle(), policy, &sch_params))
{
std::cerr << "Failed to set Thread scheduling" << std::endl;
}
}
int main()
{
std::thread T_interrupt(TickTimerInterruptFunc);
setScheduling(T_interrupt, SCHED_FIFO, 1);
std::thread T_main(MainApplicationFunc);
setScheduling(T_main, SCHED_FIFO, 20);
T_main.join();
T_interrupt.join();
}
I found several solutions for this issue and I thought I'd share them here for everybody else. Throughout stackoverflow I found others who asked similar questions to this one and there are several possible solutions.
Possible Solutions to Implement interrupt behavior with threads:
Force a context switch on your thread. I found some useful reference to how to do this on Windows as depicted in FreeRTOS Windows Simulator. For me personally, this seems to be the best option. Moreover, I might just use this simulator instead of building my own.
Write a windows driver as mentioned here: https://stackoverflow.com/a/13819216/4441211
Use SuspendThread and ResumeThread. Although when using this method you should be aware that they are async in nature as depicted here so this is not ideal.

Force program termination if threads block in C++

When a class is responsible for managing a thread, it is a common pattern (see for example here) to join this thread in the destructor after you have made sure that the thread will finish in time. However, this is not always trivial as outlined in the linked thread leading to a program that never terminates if done incorrectly. Given below is an example to reproduce such a situation:
#include <iostream>
#include <thread>
#include <chrono>
using namespace std::chrono_literals;
class Foo {
public:
Foo() {
mythread = std::thread([&](){
int i = 0;
while(running) {
std::cout << "hi" << std::endl;
if (i++ >= 2) {
// placeholder for e.g. a blocking condition variable
std::this_thread::sleep_for(1000h);
}
std::this_thread::sleep_for(500ms);
}
});
}
~Foo() {
running = false;
mythread.join();
}
private:
std::thread mythread;
bool running{true};
};
int main() {
Foo bar;
std::this_thread::sleep_for(1s);
// enabling this line will block the termination
//std::this_thread::sleep_for(2s);
std::cout << "ending" << std::endl;
}
What I am searching for is a solution that forcefully terminates the program if this situation occurs. Of course, one should always strive towards finishing the thread properly, but having such feature would be good as last resort to have a peace of mind, especially for unobserved embedded systems where crashing programs can be easier restored and debugged than blocking programs.
A rough solution draft would be to start a thread at the end of the main that sleeps for a few seconds and if the program has not ended after that time, std::terminate is called (and ideally a corresponding error is reported). However, we have a chicken-or-egg problem because this new thread will of course keep the program from ending in time. I would highly appreciate any ideas.
EDIT: The solution should not require modification of the Foo class itself so that it also covers respective bugs in unmodified code of e.g. external libraries. Ideally, it would even cover threads no class feels responsible for ending them before the main ends (classes with static storage duration or even no longer referenced objects with dynamic storage duration), but that might not be possible at all without in-depth OS hacking or an external process monitor.
There are several solutions:
Investigate and fix the root problem (this is the best and correct solution)
Workarounds:
You can notify from thread about exiting via condition variable. And only after it do join. If CV's wait_for returns with timeout - kill thread (bad solution, there are another problems).
You can create watch-thread, which will verify time-counter. Counter should be reset from time to time by the application. If watch-thread detects too high value in time-counter, it restarts whole the application.
Move suspicious code out of your application to separate process and communicate with it via IPC. In case of problems - restart that application (best among the workarounds)

Run an app and forget in a portable way

I am writing a small updater utility that is being called from the main program. The main program terminates right after the call and lets the updater copy all the updated files and then it should re-launch the main program. However that last bit is starting to give me a headache.
I can run the program with std::system (I know, unsafe, but portable) just fine but then the updater just hangs there waiting for the main program to finish. I was searching for ways to make the call fire & forget and the threads seems like the best idea.
However this:
std::system("app");
hangs the updater as it waits for return from system. Whereas this:
std::thread(std::system, "app").detach();
nor variant
std::thread t(std::system, "app");
t.detach();
seem to do anything. But when I join the thread with:
std::thread t(std::system, "app");
t.join();
it does run the app but still waits for its return just like in the original code. Why can't the detached thread run the app?
Any thread, whether detached or not, will die if its process finishes(on most systems). Give some time before the updater end execution, and the thread may be able to actually make the call:
#include <chrono>
#include <cstdlib>
#include <thread>
void do_app() {
std::system("app");
}
int main() {
std::thread(do_app).detach();
std::this_thread::sleep_for(std::chrono::seconds(2));
}
I would just use ifdef blocks around the different implementations. For Windows you can use CreateProcess, linux (and probably Mac) supports POSIX popen / fork methods.
std::system does not really make your program portable, usually the syntax for invoking things on the shell differs slightly from platform to platform and you end up with platform dependent code anyways.
Here is a detailed tutorial on how to do it in Linux:
http://www.yolinux.com/TUTORIALS/ForkExecProcesses.html
And for Windows:
https://msdn.microsoft.com/en-us/library/windows/desktop/ms682425(v=vs.85).aspx

Can I interrupt function if it is executed for too long?

I a have third party function which I use in my program. I can't replace it; it's in a dynamic library, so I also can't edit it. The problem is that it sometimes runs for too long.
So, can I do anything to stop this function from running if it runs more than 10 seconds for example? (It's OK to close program in this scenario.)
PS. I have Linux, and this program won't have to be ported anywhere else.
What I want is something like this:
#include <stdio.h>
#include <stdlib.h>
void func1 (void) // I can not change contents of this.
{
int i; // random
while (i % 2 == 0);
}
int main ()
{
setTryTime(10000);
timeTry{
func1();
} catchTime {
puts("function executed too long, aborting..");
}
return 0;
}
Sure. And you'd do it just the way you suggested in your title: "signals".
Specifically, an "alarm" signal:
http://linux.die.net/man/2/alarm
http://beej.us/guide/bgipc/output/html/multipage/signals.html
If you really have to do this, you probably want to spawn a process that does nothing but invoke the function and return its result to the caller. If it runs too long, you can kill that process.
By putting it into its own process, you stand a decent (not great, but decent) chance of cleaning up at least most of what it was doing so when it dies unexpectedly it probably won't make a complete mess of things that will lead to later problem.
The potential problem with forcefully cancelling a running function is that it may "own" resources that it intended to return later. The kind of resources that can be problems include:
heap memory allocations (free store)
shared memory segments
threads
sockets
file handles
locks
Some of these resources are managed on a per-process basis, so letting the function run in a different process (perhaps using fork) makes it easier to kill cleanly. Other resources can outlive a process, and really must be cleaned up explicitly. Depending on your operating system, it's also possible that the function may be part-way through interacting with some hardware driver or device, and killing it unexpectedly may leave that driver or device in a bizarre state such that it won't work until after a restart.
If you happen to know that the function doesn't use any of these kind of resources, then you can kill it confidently. But, it's hard to guarantee that: in a large system with many such decisions - which the compiler can't check - evolution of code in functions like func1() is likely to introduce dependencies on such resources.
If you must do this, I'd suggest running it in a different process or thread, and using kill() for processes, pthread_kill if func1() has some support for terminating when a flag is set asynchronously, or the non-portable pthread_cancel if there's really no other choice.

Is it possible to use pthreads without pthread_join()?

What I've noticed recently in attempting to add some multithreaded functionality to some code of mine for a project at work is that pthreads are a huge pain in the ass to deal with logistically...
Here's the scenario...
I have an infinite loop in my main method (a server) spawning threads to deal with data whenever it receives a packet from whatever client. The problem is that I can't get the threads to execute concurrently at all. They refuse to begin execution until a call to pthread_join() from the main method, which completely kills the whole purpose of using threads in the first place (server needs to STOP execution flow, and wait for the thread to finish processing its data before receiving anymore packets! ridiculous.)
So is there a way to use pthreads and have them actually be multithreaded? Or am I better off not using threads at all, and saving the extra resources by stopping execution in my server to call a function to process data?
I'm thinking I may have to resort to forking everytime...
This is frustrating....
some sample code i did is below:
// gcc threads.c -lpthread
#include <stdio.h>
#include <pthread.h>
struct point{
int x, y;
};
static void *print_point(void *point_p);
int main() {
pthread_t tid;
struct point pt = {3, 5};
printf("enter main\n");
pthread_create(&tid, NULL, print_point, &pt);
while(1){continue;}
return 0;
}
static void *print_point(void *point_p) {
struct point arg = * (struct point *) point_p;
printf("Point: (%d, %d)\n", arg.x, arg.y);
return NULL;
}
when I run and compile that (yes i compile with the -lpthread switch), it prints "enter main" and doesn't execute the thread... I even let it run for a while (got up, went to the bathroom, ate some food), and still nothing.
So since the main method spawns a thread then loops infinitely, the thread should eventually execute... right? From what I can tell from my tests the main method never gives up execution to the thread it spawned. The only way I can get it to give it up it by calling join (but that defeats the purpose of having threads since main will wait around until the thread is done).
You're never giving the thread a chance to execute with that while(1){continue;}. One of two things will happen here.
You've compiled with high enough optimization that the compiler makes that entire loop vanish. The thread never gets a chance to execute because main starts the thread and then immediately returns zero.
The compiler doesn't optimize the loop away. With this busy loop you once again are not giving the thread mechanism a chance to slip in.
Add a sleep (0); call to the body of that busy loop.
Actually your code works fine for me, but I think your problem is that the main thread is sitting in that while() loop, hogging all the CPU usage, so the second thread never gets a chance. The fact that pthread_join makes it work is a bit of a red herring: it's just stopping the main thread so the other threads get a chance.
Obviously the right fix for this is to make the main thread sleep properly when it has nothing to do. For your test code, try putting sleep(1) in your while loop.