Skip to content

Instantly share code, notes, and snippets.

@IgorKarymov
Created September 18, 2011 09:22
Show Gist options
  • Save IgorKarymov/1224897 to your computer and use it in GitHub Desktop.
Save IgorKarymov/1224897 to your computer and use it in GitHub Desktop.
riak if_not_modified
-module(test).
-export([
test/0
]).
-define(RIAK_HOST, "127.0.0.1").
-define(RIAK_PORT, 8087).
test() ->
{ok, Pid} = riakc_pb_socket:start_link(?RIAK_HOST, ?RIAK_PORT),
StartValue = term_to_binary(1),
NewObj = riakc_obj:new(<<"counters">>, <<"counter">>, StartValue),
ok = riakc_pb_socket:put(Pid, NewObj),
Res = parmap(fun get_autoincrement_counter/1, lists:duplicate(20, 3)),
riakc_pb_socket:stop(Pid),
Res.
get_autoincrement_counter(Repeats) ->
{ok, Pid} = riakc_pb_socket:start_link(?RIAK_HOST, ?RIAK_PORT),
Res = autoincrement_loop(Pid, Repeats),
riakc_pb_socket:stop(Pid),
Res.
autoincrement_loop(_Pid, 0) -> {error, repeats};
autoincrement_loop(Pid, Repeats) ->
{ok, RiakObj} = riakc_pb_socket:get(Pid, <<"counters">>, <<"counter">>),
Value = riakc_obj:get_value(RiakObj),
DecodedValue = binary_to_term(Value),
NewObj = riakc_obj:update_value(RiakObj, term_to_binary(DecodedValue + 1)),
case riakc_pb_socket:put(Pid, NewObj, [if_not_modified]) of
ok -> DecodedValue;
{error, Reason} ->
io:format("reason ~p~n", [Reason]),
autoincrement_loop(Pid, Repeats - 1)
end.
parmap(F, L) ->
Parent = self(),
[receive {Pid, Result} -> Result after 5000 -> {error, timeout} end ||
Pid <- [spawn(fun() ->
Parent ! {self(), F(X)} end) || X <- L]].
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment