Skip to content

Instantly share code, notes, and snippets.

@ivcn
ivcn / TestRandom.cpp
Last active February 17, 2017 12:14
Implementation of some statistical distributions using C++11 <chrono> and <random> libraries
#include <chrono>
#include <iostream>
#include <random>
#include <vector>
using std::cout;
using std::endl;
using std::vector;
class TestRandom {
'''
Consider next number sequence
F(1) = 1
F(2) = 2
F(3) = 3
F(n) = 1*F(n-1) + 2*F(n-2) + 3*F(n-3)
Here we are interested only in parity of numbers.
'''
@ivcn
ivcn / spawn.cpp
Created February 21, 2017 23:23
An example of asynchronous launching of some functions
template<typename F,typename A>
std::future<std::result_of<F(A&&)>::type>
spawn(F&& f,A&& a)
{
typedef std::result_of<F(A&&)>::type result_type;
std::packaged_task<result_type(A&&)>
task(std::move(f)));
std::future<result_type> res(task.get_future());
std::thread t(std::move(task),std::move(a));
t.detach();
@ivcn
ivcn / loop.js
Created March 5, 2017 21:36
Loop with timeout in JavaScript
var i = 0;
function loop () {
setTimeout(function () {
doSomething();
i++;
if (i < 20) {
loop();
}
}, 300)
}
template<typename T, size_t n>
void copy_array(T (&src)[n], T (&dst)[n])
{
for (size_t i = 0; i < n; i++)
{
dst[i] = src[i];
}
}
int main()
@ivcn
ivcn / print.cpp
Created April 6, 2017 13:43
How to send several values to stream until C++17
template<typename... Args>
void print(Args&&... args) {
using dummy = int[];
(void)dummy{0, (void(cout << std::forward<Args>(args)), 0)...};
cout << endl;
}
@ivcn
ivcn / thread_handle.cpp
Created April 6, 2017 14:05
Wrapper for std::thread. Provides automatic join of owned thread.
class thread_handle {
private:
std::thread t;
int id;
public:
template<typename F, typename... Args>
thread_handle(int _id, F&& f, Args&&... args) :
id(_id),
t(std::move(std::thread(f, args...))) {
@ivcn
ivcn / deadlock.cpp
Created April 7, 2017 11:31
Simple deadlock example in C++
int main() {
std::mutex m1;
std::mutex m2;
std::thread t1([&m1, &m2] {
print("1. Acquiring m1.");
m1.lock();
std::this_thread::sleep_for(std::chrono::milliseconds(10));
print("1. Acquiring m2");
m2.lock();
});
@ivcn
ivcn / test.glsl
Created April 8, 2017 11:10
simple 2D shader
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
vec2 center = iResolution.xy / 2.0;
float r1 = iResolution.y / 5.0;
float r2 = iResolution.y / 3.0;
vec2 uv = fragCoord.xy / iResolution.xy;
float dist = distance(fragCoord.xy, center);
if( dist >= r1 && dist <= r2) {
float d = (dist-r1)/(r2-r1);
@ivcn
ivcn / producer_consumer.cpp
Created April 9, 2017 16:04
Simple implementation of producer-consumre pattern in C++
template<typename ElementType>
class Queue {
public:
Queue(size_t size) :
buffer(size),
front(0),
end(0) {}
void push(ElementType newElement) {
std::unique_lock<std::mutex> lk(m);