Thursday, April 18, 2019

Run Powershell with elevate without prompt - verb runas start-process


Based on https://ss64.com/ps/syntax-elevate.html this:


Create a script as :

$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition
If (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator))

{

  # Relaunch as an elevated process:

  Start-Process powershell.exe   "-File",('"{0}"' -f $MyInvocation.MyCommand.Path) -Verb RunAs

  exit

}

# Now running elevated so launch the script:

& $scriptPath + "\test.ps1" "Long Argument 1" "Long Argument 2"

To disable the UAC pop up windows

REG ADD HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v ConsentPromptBehaviorAdmin /t REG_DWORD /d 0 /f

Tuesday, April 16, 2019

c++ mutithreading mistakes

https://www.acodersjourney.com/top-20-cplusplus-multithreading-mistakes/

Mistake # 1: Not using join() to wait for background threads before terminating an application
If we forgot to join a thread or detach it(make it unjoinable) before the main program terminates, it'll cause in a program crash.

Mistake # 2: Trying to join a thread that has been previously detached
If you have detached a thread and at some point, you cannot rejoin it to the main thread.
The problem is that this'll not cause a compilation error,  instead it'll crash your program.

Mistake # 3: Not realizing that std::thread::join() blocks the calling thread

Mistake # 4: Thinking that thread function arguments are pass by reference by default
Thread function arguments are by default pass by value. So if you need the change persisted in the arguments passed in, you'll need to pass them by reference using std::ref().

Mistake # 5: Not protecting shared data or shared resources with a critical section (eg. mutex)
In a multithreaded environment, more than one thread is often competing for a resource or shared data. This often results in undefined behavior for the resource or data , unless the resource or data is protected using some mechanics that only allows ONE thread to act on it at a time.

Mistake # 6: Forgetting to release locks after a critical section
should use std::lock_guard which uses RAII style to manage the duration of mutex lock. 

Mistake # 7: Not keeping critical sections as compact and small as possible


Mistake # 8 : Not acquiring multiple locks in the same order
This is one of the most common causes of DEADLOCK

Mistake # 10: Using mutexes when std::atomic types will suffice
When you have simple data types that needs to be updated, for example, a simple bool or a integer counter, using std:atomic will almost yield better performance than using a mutex.

Mistake # 11: Creating and Destroying a lot of threads directly when using a thread pool is available
Two of the most popular libraries that implements thread pools are Intel Thread Building Blocks(TBB) and Microsoft Parallel Patterns Library(PPL).

Mistake # 12: Not handling exceptions in background threads
Exceptions thrown in one thread cannot be caught in another thread

Mistake # 13: Using threads to simulate Asyn jobs when std::async will do
If you just need some code executed asynchronously i.e. without blocking execution of Main thread, your best bet is to use the std::async functionality to execute the code. 

Mistake # 14: Not using std::launch::async if asynchronicity is desired
std::async is a bit of a misnomer because the function in it's default form may not execute in an asynchronous way !


Mistake # 15: Calling .Get() on a std::future in a time sensitive code path

Mistake # 16: Not realizing that an exception thrown inside an async task is propagated when std::future::get() is invoked.

Mistake # 17: Using std::async when you need granular control over thread execution
Mistake # 18: Creating many more "Runnable" threads than available cores

Mistake # 19: Using "volatile" keyword for synchronization
The "volatile" keyword in front of a variable type declaration does not make the operations on that variable atomic or thread safe in any way. What you probably want is an std::atomic.

Mistake # 20: Using a Lock Free architecture unless absolutely needed



c++ Multithreading


1 Header Required:
#include <thread>

2 We can attach a callback with the std::thread object, that will be executed when this new thread starts.
These callbacks can be:
a.) Function Pointer
b.) Function Objects
c.) Lambda functions

3 Joining Threads with std::thread::join()
std::thread th(funcPtr);
th.join();

Detaching Threads using std::thread::detach()
std::thread th(funcPtr);
th.detach();

1.) Never call join() or detach() on std::thread object with no associated executing thread
2.) Never forget to call either join or detach on a std::thread object with associated executing thread

4 Pass Arguments to Threads
By default all arguments are copied into the internal storage of new thread.
Don’t pass addresses of variables from local stack to thread’s callback function.
Be careful while passing pointer to memory located on heap to thread. Because it might be possible that some thread deletes that memory before new thread tries to access it.
As arguments are copied to new threads stack so, if you need to pass references in common way.  ie.
   void threadCallback(int const & x)
   {
       int & y = const_cast<int &>(x);
       y++;
   }
   int main()
   {
    int x = 9;
    std::thread threadObj(threadCallback,std::ref(x));
    threadObj.join();
    return 0;
    }

Assigning pointer to member function of a class as thread function:
Pass the pointer to member function as callback function and pass pointer to Object as second argument.

#include <thread>
class DummyClass {
public:
    DummyClass()
    {}
    DummyClass(const DummyClass & obj)
    {}
    void sampleMemberFunction(int x)
    {
        std::cout<<"Inside sampleMemberFunction "<<x<<std::endl;
    }
};
int main() {

    DummyClass dummyObj;
    int x = 10;
    std::thread threadObj(&DummyClass::sampleMemberFunction,&dummyObj, x);
    threadObj.join();
    return 0;
}

5 std::mutex
There are two important methods of mutex:
a.) lock()
b.) unlock()
std::lock_guard
std::lock_guard is a class template, which implements the RAII RESOURCE ACQUISITION IS INITIALIZATION (RAII) for mutex.
It wraps the mutex inside it’s object and locks the attached mutex in its constructor. When it’s destructor is called it releases the mutex.

Condition Variables.
Condition Variable is a kind Event used for signaling between 2 threads. One thread can wait for it to get signaled, while other thread can signal this.

7std::future is a class template and its object stores the future value.
Now what the hell is this future value.
Actually a std::future object internally stores a value that will be assigned in future and it also provides a mechanism to access that value i.e. using get() member function. But if somebody tries to access this associated value of future through get() function before it is available, then get() function will block till value is not available.
std::promise is also a class template and its object promises to set the value in future. Each std::promise object has an associated std::future object that will give the value once set by the std::promise object.
A std::promise object shares data with its associated std::future object.

If std::promise object is destroyed before setting the value the calling get() function on associated std::future object will throw exception.
A part from this, if you want your thread to return multiple values at different point of time then just pass multiple std::promise objects in thread and fetch multiple return values from thier associated multiple std::future objects.

Wednesday, April 3, 2019

STL Overview

STL Overview
Containers:
Sequence: vector deque list
Associative: set, multiset, map, multimap

Iterators:
Input, output, forward, bidirectional, random access
Each container declares a trait for the type of iterator it provides

Generic Algorithms:
Sequence (mutating and non-mutating) sorting numeric

STLContainers are Abstract Data Types
All Containers are parameterized by the type they contain
Sequence containers are ordered
Associative containers are unordered
Each container declares an iterator typedef trait
Each container provides special factory methods for iterators

What's STL? Why use STL?

What's STL? Why use STL?

The Standard Template Library provides a set of well structured generic C++ components that work together in a seamless way.
–AlexanderStepanov&MengLee, The Standard Template Library
A collection of composable class and function templates.
- Helper class and function templates, operators, pair
- Container and iterator class templates
- Generic algorithms that operate over iterators
- Function objects
- Adaptors


Enables generic programming in c++
-Each generic algorithm can operate over any iterator for which the necessary operations are provided.
-Extensible can support new algorithm containers iterators
Resue
The STL hides complex tedious and error-prone details
Typesafe plug compatibility between STL component
Flexibility
Iterator decouple algorithms for containers
Unanticipated combinations easily supported
Efficiency
Templates avoid virtual function overhead
Strict attention to the time complexity of algorithms